﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Net;
using System.Net.Http;
using System.Net.WebSockets;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
using System.Web;
using System.Web.Http;
using System.Web.Http.Description;
using System.Web.Http.ModelBinding;
using System.Web.WebPages;
using AspNet.Identity.MongoDB;
using Microsoft.Ajax.Utilities;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.Owin;
using MongoDB.Bson;
using MongoDB.Driver;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using SignatureWebApi.Models;
using BCrypt.Net;
namespace SignatureWebApi.Controllers
{
    /// <summary>
    /// 签单数据控制类
    /// </summary>
    [RoutePrefix("api/Signature")]
    [Authorize(Roles = "DataRead")]
    public class SignatureStoreController : ApiController
    {
        ///// <summary>
        ///// 获取航班信息(手机)
        ///// </summary>
        ///// <param name="model">手机航班数据请求模型</param>
        ///// <returns>返回航班数据</returns>
        //[Route("GetMobileFlightList")]
        //public HttpResponseMessage GetMobileFlightList([FromUri]FlightRequestMobileModels model)
        //{
        //    if (!ModelState.IsValid)
        //    {
        //        return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);

        //    }
        //    var mongoDb = MongoDbInstanceStore.DataStoreInstance;
        //    var builder = Builders<FlightReturnMobileModels>.Filter;
        //    FilterDefinition<FlightReturnMobileModels> filter;
        //    if (model==null)
        //    {
        //           filter = builder.Empty;
                
        //    }
        //    else
        //    {
        //        Type modelType = model.GetType();
        //        PropertyInfo[] propertyList = modelType.GetProperties();
        //        filter = builder.Empty;
        //        foreach (PropertyInfo item in propertyList)
        //        {
        //            string name = item.Name;
        //            object value = item.GetValue(model);
        //            if (value != null)
        //            {
        //                if (name != "Area")
        //                {
        //                    filter &= builder.Eq(name, value);
        //                }
        //                else
        //                {
        //                    var standArea= new StandArea();
        //                    var type = standArea.GetType().GetProperty(model.Area.ToString());
        //                    if (type!=null)
        //                    {
        //                        var values = type.GetValue(standArea) as IEnumerable<string>;
        //                        filter &= builder.In(x => x.Stand, values);
        //                    }
        //                    else
        //                    {
        //                        filter &= builder.In(x => x.Stand, new string[] { });
        //                    }
        //                }
        //            }
        //        }
        //    }
        //    var dBdata=mongoDb.GetDataMany<FlightReturnMobileModels, FlightReturnMobileModels>("DataStore", "FlightStore", filter);
        //    return Request.CreateResponse(HttpStatusCode.OK, dBdata);
        //    //return dBdata;
        //    //return Request.CreateResponse(HttpStatusCode.OK, returnData);
        //}
        ///// <summary>
        ///// 获取航班信息(网页)
        ///// </summary>
        ///// <param name="model">网页航班数据请求模型</param>
        ///// <returns>返回航班数据<see cref="FlightReturnWebModels"/></returns>
        //[Route("GetWebFlightList")]
        //public HttpResponseMessage GetWebFlightList([FromUri]FlightRequestWebModels model)
        //{
        //    if (!ModelState.IsValid)
        //    {
        //        return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
        //    }
        //    var mongoDb = MongoDbInstanceStore.DataStoreInstance;
        //    var builder = Builders<FlightReturnWebModels>.Filter;
        //    FilterDefinition<FlightReturnWebModels> filter;
        //    if (model == null)
        //    {
        //        filter = builder.Empty;

        //    }
        //    else
        //    {
        //        Type modelType = model.GetType();
        //        PropertyInfo[] propertyList = modelType.GetProperties();
        //        filter = builder.Empty;
        //        foreach (PropertyInfo item in propertyList)
        //        {
        //            string name = item.Name;
        //            object value = item.GetValue(model);
        //            if (value != null)
        //            {
        //                if (name != "Area")
        //                {
        //                    if (value.GetType().IsEnum)
        //                    {
        //                        value = ((int)value).ToString();
        //                        //filter &= builder.Eq(name, StatusFilter);

        //                    }
        //                    filter &= builder.Eq(name, value);
        //                }
        //                else
        //                {
        //                    var standArea = new StandArea();
        //                    var type = standArea.GetType().GetProperty(model.Area.ToString());
        //                    if (type != null)
        //                    {
        //                        var values = type.GetValue(standArea) as IEnumerable<string>;
        //                        filter &= builder.In(x => x.Stand, values);
        //                    }
        //                    else
        //                    {
        //                        filter &= builder.In(x => x.Stand, new string[] { });
        //                    }
        //                }
        //            }
        //        }
        //    }
        //    var dBdata = mongoDb.GetDataMany< FlightReturnWebModels, FlightReturnWebModels>("DataStore", "FlightStore", filter);
        //    //return dBdata;
        //    return Request.CreateResponse(HttpStatusCode.OK, dBdata);
        //}
        ///// <summary>
        ///// 创建签单(要修改)
        ///// </summary>
        ///// <param name="model">创建签单数据模型</param>
        ///// <returns>返回HTTP返回码,如出错,将同时返回出错信息。<see cref="HttpStatusCode"/></returns>
        //[Route("CreateSignatureList")]
        //public HttpResponseMessage CreateSignatureList(SignatureCreateModel model)
        //{
        //    if (model==null)
        //    {
        //        ModelState.AddModelError("error", "参数不能为空.");
        //        return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
        //    }

        //    if (!ModelState.IsValid)
        //    {
        //        return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
        //    }
        //    {
        //        SignatureMongoDbInstance mongoDb = MongoDbInstanceStore.DataStoreInstance;
        //        var assistfilter = new BsonDocument(new Dictionary<string, object>()
        //        {
        //            {"func", "ListCountOnline"}
        //        });
        //        var dateInDb = mongoDb.GetDataSingel("DataStore", "DataAssist", assistfilter);
        //        var store = dateInDb["store"] as BsonDocument;
        //        if (store == null)
        //        {
        //            ModelState.AddModelError("error", new NullReferenceException());
        //            return Request.CreateErrorResponse(HttpStatusCode.Accepted, ModelState);
        //        }
        //        BsonDateTime dateBsonValue = null;
        //        BsonInt32 countBsonValue = null;
        //        foreach (var obj in store)
        //        {
        //            switch (obj.Name)
        //            {
        //                case "Date": { dateBsonValue = obj.Value as BsonDateTime; } break;
        //                case "Count": { countBsonValue = obj.Value as BsonInt32; } break;
        //            }
        //        }
        //        if (dateBsonValue == null || countBsonValue == null)
        //        {
        //            ModelState.AddModelError("error", new NullReferenceException());
        //            return Request.CreateErrorResponse(HttpStatusCode.Accepted, ModelState);
        //        }
        //        var dbTime = dateBsonValue.ToLocalTime();
        //        var listCount = countBsonValue.Value;
        //        DateTime todayDateTime = DateTime.Now;
        //        var datePart = todayDateTime.ToString("yyyyMMdd");
        //        string format;
        //        var yearDvalue = todayDateTime.Year - dbTime.Year;
        //        var monthDvalue = todayDateTime.Month - dbTime.Month;
        //        var dayDvalue = todayDateTime.Day - dbTime.Day;
        //        if (yearDvalue == 0 && monthDvalue == 0 && dayDvalue == 0)
        //        {
        //            listCount += 1;
        //            format = $"{listCount:0000}";
        //        }
        //        else
        //        {
        //            listCount = 1;
        //            format = $"{listCount:0000}";
        //        }
        //        var No = datePart + format;
        //        var addDocument = model.ToBsonDocument();
        //        addDocument.Add("No", No);
        //        var createResult=mongoDb.InsertSingleDocument("DataStore", "SignatureStore", addDocument);

        //        if (createResult == 1)
        //        {
        //            var builder = Builders<FlightReturnMobileModels>.Filter;
        //            var filter = builder.Eq(x => x.Id, model.MissionId);
        //            var updateContent = new BsonDocument(new Dictionary<string, object>()
        //            {
        //                {"OrderTakingTime", DateTime.Now}
        //            });
        //            var updateResult=mongoDb.UpdateSingleDocument("DataStore", "FlightStore",filter,updateContent);
        //            if (updateResult!=1)
        //            {
        //                var delFilter=new BsonDocument(new Dictionary<string, object>()
        //                {
        //                    {"No", No}
        //                });
        //                mongoDb.DelSingleDocument("DataStore", "SignatureStore", delFilter);
        //                ModelState.AddModelError("error", "新增表单失败(无法更新任务信息).");
        //                return Request.CreateErrorResponse(HttpStatusCode.Accepted, ModelState);
        //            }
        //            ListCountStore updateStore = new ListCountStore() { Date = todayDateTime, Count = listCount };
        //            model.UpdateListCount(updateStore);
        //        }
        //        else
        //        {
        //            ModelState.AddModelError("error", "新增表单失败(无法插入document).");
        //            return Request.CreateErrorResponse(HttpStatusCode.Accepted, ModelState);
        //        }

        //        return new HttpResponseMessage(HttpStatusCode.OK);
        //    }
        //}
        /// <summary>
        /// 更新系统创建的签单的数据
        /// </summary>
        /// <param name="model">在线更新签单数据模型</param>
        /// <returns>返回HTTP返回码,如出错,将同时返回出错信息。<see cref="HttpStatusCode"/></returns>
        [Route("UpdateSysBuildSignatureList")]
        public HttpResponseMessage UpdateSysBuildSignatureList(SignatureUpdateModel model)
        {
            if (model == null)
            {
                ModelState.AddModelError("error", "参数不能为空.");
                return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
            }
            if (!ModelState.IsValid)
            {
                return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
            }
            {
                var mongoDb = MongoDbInstanceStore.DataStoreInstance;
                var addDocument = model.ToBsonDocument();
                if (model.Pic==null)
                {
                    addDocument.Remove("Pic");
                }

                if (model.StaffSignPic==null)
                {
                    addDocument.Remove("StaffSignPic");
                }
                addDocument.Remove("No");
                addDocument.Remove("Status");
                addDocument.Remove("Airline");
                addDocument.Remove("FType");
                addDocument.Remove("Stand");
                addDocument.Remove("PlaneType");
                addDocument.Remove("Pnum");
                addDocument.Remove("Flt");
                addDocument.Remove("LastUpdateType");
                addDocument.Add("LastUpdateType", SignatureUpdateType.ManaulOnline);
                addDocument.Add("User", User.Identity.GetUserName());
                addDocument.Add("UpdateTime", DateTime.Now);
                var userManager = Request.GetOwinContext().GetUserManager<ApplicationUserManager>();
                var userContext = userManager.FindById(User.Identity.GetUserId());
                var userRealName = userContext.RealName;
                addDocument.Add("UserName", userRealName);
                var builder = Builders<SignatureUpdateModel>.Filter;
                var filter = builder.Eq(x => x.No, model.No)&builder.Ne(x=>x.Status, SignatureStatus.已删除)& builder.Ne(x => x.Status, SignatureStatus.已完结) & builder.Eq("SysBuild", true);
                var result = mongoDb.UpdateSingleDocument("DataStore", "SignatureStore", filter, addDocument);
                if (result==1)
                {
                    return new HttpResponseMessage(HttpStatusCode.OK);
                }

                    ModelState.AddModelError("err","更新签单失败");
                    return Request.CreateErrorResponse(HttpStatusCode.Accepted, ModelState);
                //Request.CreateResponse(HttpStatusCode.OK, product);
            }
        }
        /// <summary>
        /// 更新手动创建的签单的数据
        /// </summary>
        /// <param name="model">在线更新签单数据模型</param>
        /// <returns>返回HTTP返回码,如出错,将同时返回出错信息。<see cref="HttpStatusCode"/></returns>
        [Route("UpdateManaulBuildSignatureList")]
        public HttpResponseMessage UpdateManaulBuildSignatureList(SignatureUpdateModel model)
        {
            if (model == null)
            {
                ModelState.AddModelError("error", "参数不能为空.");
                return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
            }
            if (!ModelState.IsValid)
            {
                return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
            }
            {
                var mongoDb = MongoDbInstanceStore.DataStoreInstance;
                var addDocument = model.ToBsonDocument();
                if (model.Pic == null)
                {
                    addDocument.Remove("Pic");
                }

                if (model.StaffSignPic == null)
                {
                    addDocument.Remove("StaffSignPic");
                }
                addDocument.Remove("No");
                addDocument.Remove("Status");
                addDocument.Remove("LastUpdateType");
                addDocument.Add("LastUpdateType", SignatureUpdateType.ManaulOffline);
                addDocument.Add("User", User.Identity.GetUserName());
                addDocument.Add("UpdateTime", DateTime.Now);
                var userManager=Request.GetOwinContext().GetUserManager<ApplicationUserManager>();
                var userContext = userManager.FindById(User.Identity.GetUserId());
                var userRealName = userContext.RealName;
                addDocument.Add("UserName", userRealName);
                var builder = Builders<SignatureUpdateModel>.Filter;
                var filter = builder.Eq(x => x.No, model.No) & builder.Ne(x => x.Status, SignatureStatus.已删除) & builder.Ne(x => x.Status, SignatureStatus.已完结)&builder.Ne("SysBuild",true);
                var result = mongoDb.UpdateSingleDocument("DataStore", "SignatureStore", filter, addDocument);
                if (result == 1)
                {
                    return new HttpResponseMessage(HttpStatusCode.OK);
                }

                ModelState.AddModelError("err", "更新签单失败");
                return Request.CreateErrorResponse(HttpStatusCode.Accepted, ModelState);
                //Request.CreateResponse(HttpStatusCode.OK, product);
            }
        }
        /// <summary>
        /// 将离线创建的签单列表同步到数据库
        /// </summary>
        /// <param name="model">离线同步签单模型</param>
        /// <returns>返回HTTP返回码,如出错,将同时返回出错信息。<see cref="HttpStatusCode"/></returns>
        [Route("syncUpdateSignatureList")]
        public HttpResponseMessage SyncSignatureList(OfflineSignatureUpdateModel model)
        {
            if (model == null)
            {
                ModelState.AddModelError("error", "不能同步空数据.");
                return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
            }
            if (!ModelState.IsValid)
            {
                return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
            }
            var mongoDb = MongoDbInstanceStore.DataStoreInstance;
            var builder = Builders<OfflineSignatureUpdateModel>.Filter;
            var filter = builder.Eq(x => x.No, model.No);
            var rCount = mongoDb.CountData("DataStore", "SignatureStore", filter);
            if (rCount > 0)
            {
                ModelState.AddModelError("error", "已有重复表单号.");
                return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
            }
            var addDocument = model.ToBsonDocument();
            addDocument.Add("Status", SignatureStatus.已签名);
            var userManager = Request.GetOwinContext().GetUserManager<ApplicationUserManager>();
            var userContext = userManager.FindByName(model.UserId);
            var userRealName = userContext.RealName;

            addDocument.Add("IsBind", false);
            {
                //检查并绑定离线航班
                //先在签单列表数据库中寻找此离线签单的自动生成的签单版本并获得自动生成的签单号,根据此签单号在航班任务列表中寻找该航班任务并添加绑定 并更新已有的自动签单数据
                var FltString = model.Flt;
                if (!FltString.Contains('/'))
                {
                    ModelState.AddModelError("error", "航班号输入错误.");
                    return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
                }
                var FltIn = FltString.Split('/')[0];
                var FltOut = FltString.Split('/')[1];

                var CheckFilterBuilder = Builders<SignatureCheckReturnModel>.Filter;
                //CheckFilter
                var FltInFilter = CheckFilterBuilder.Regex("Flt", new BsonRegularExpression(".*" + FltIn + ".*", "i"));
                var FltOutFilter = CheckFilterBuilder.Regex("Flt", new BsonRegularExpression(".*" + FltOut + ".*", "i"));
                var FltCheckFilter = CheckFilterBuilder.And(FltInFilter, FltOutFilter);
                var TimeCheckFilter1 = CheckFilterBuilder.Gte("Time", model.Time.Date);
                var TimeCheckFilter2 = CheckFilterBuilder.Lt("Time", model.Time.Date.AddDays(1));
                var BuildCheckFilterTrue = CheckFilterBuilder.Eq("SysBuild", true);
                var BuildCheckFilterFalse = CheckFilterBuilder.Eq("SysBuild", false);
                var TypeCheckFilter = CheckFilterBuilder.Eq("SType", SignatureType.普通);
                var BindCheckFilter = CheckFilterBuilder.Eq("IsBind", true);
                var AbandonedFilter = CheckFilterBuilder.Or(CheckFilterBuilder.Eq("abandoned", false), CheckFilterBuilder.Not(CheckFilterBuilder.Exists("abandoned")));
                var SysCheckFilter = CheckFilterBuilder.And(FltCheckFilter, TimeCheckFilter1, TimeCheckFilter2, BuildCheckFilterTrue,AbandonedFilter);
                var ManualCheckFilter = CheckFilterBuilder.And(FltCheckFilter, TimeCheckFilter1, TimeCheckFilter2, BuildCheckFilterFalse, TypeCheckFilter, BindCheckFilter,AbandonedFilter);

                //根据不同的签单类型或者是否重复上传判断是否需要同步更新匹配的系统生成签单,同时获取匹配的系统签单号
                var ManualCheckResult = model.SignatureType == SignatureType.普通 ? mongoDb.CountData("DataStore", "SignatureStore", ManualCheckFilter) : 0;//统计是否存在匹配的类型为Normal的手工生成签单(上传NORMAL单时判断)
                var CheckProjectionBuilder = Builders<SignatureCheckReturnModel>.Projection;
                var CheckProjection = CheckProjectionBuilder.Include(x => x.No);
                var checkResult = new SignatureCheckReturnModel();

                if (ManualCheckResult > 0 || model.SignatureType != SignatureType.普通)//发现存在这种Normal的人工生成签单或者签单状态不是Nomarl的
                {
                    if (model.SignatureType == SignatureType.普通)
                    {
                        ModelState.AddModelError("warning", "该航班已存在匹配的离线签单,此次上传的数据不会同步到系统生成的签单中.");
                    }
                    var checkResultTemp = mongoDb.GetDataSingel<SignatureCheckReturnModel, SignatureCheckReturnModel>("DataStore", "SignatureStore", SysCheckFilter) as IEnumerable<SignatureCheckReturnModel>;
                    checkResult = checkResultTemp != null ? checkResultTemp.ToList().Count > 0 ? checkResultTemp.ToList()[0] : checkResult : checkResult;
                }
                else
                {
                    var UpdateSignatureBuilder = Builders<SignatureCheckReturnModel>.Update;
                    var UpdateSignatureContent = UpdateSignatureBuilder.Set("bridgeData", model.bridgeData);
                    UpdateSignatureContent = UpdateSignatureContent.Set("pcaData", model.pcaData);
                    UpdateSignatureContent = UpdateSignatureContent.Set("adapterData", model.adapterData);
                    UpdateSignatureContent = UpdateSignatureContent.Set("psData", model.psData);
                    UpdateSignatureContent = UpdateSignatureContent.Set("pbData", model.pbData);
                    UpdateSignatureContent = UpdateSignatureContent.Set("cbData", model.cbData);
                    UpdateSignatureContent = UpdateSignatureContent.Set("gData", model.gData);
                    UpdateSignatureContent = UpdateSignatureContent.Set("adapterData", model.adapterData);
                    UpdateSignatureContent = UpdateSignatureContent.Set("UpdateTime", DateTime.Now);
                    UpdateSignatureContent = UpdateSignatureContent.Set("LastUpdateType", SignatureUpdateType.ManaulOnline);
                    UpdateSignatureContent = UpdateSignatureContent.Set("User", model.UserId);
                    UpdateSignatureContent = UpdateSignatureContent.Set("UserName", userRealName);
                    var options = new FindOneAndUpdateOptions<SignatureCheckReturnModel>
                    {
                        ReturnDocument = ReturnDocument.After,
                        Projection = CheckProjection
                    };
                    checkResult = mongoDb.FindOneAndUpdate("DataStore", "SignatureStore", SysCheckFilter, UpdateSignatureContent, options);
                }
                //根据系统前单号获取绑定的航班任务将上传的离线签单绑定到该任务上
                if (!string.IsNullOrEmpty(checkResult?.No))
                {
                    var autoNo = checkResult.No;
                    var upFMbuilder = Builders<BsonDocument>.Filter;
                    FilterDefinition<BsonDocument> upFMFilter = upFMbuilder.AnyEq("SL_Id", autoNo);
                    var updateBuilder = Builders<BsonDocument>.Update;
                    var updateSLIDcontent = updateBuilder.Push("SL_Id", model.No);
                    var updatecount = mongoDb.UpdateSingleDocument("DataStore", "FlightMissionList", upFMFilter, updateSLIDcontent);
                    addDocument.Set("IsBind", updatecount > 0);
                    if (!(updatecount>0))
                    {
                        ModelState.AddModelError("warning", "成功找到匹配的航班任务但未能成功绑定到任务中.");
                    }
                }
                else
                {
                    ModelState.AddModelError("warning", "没有找到该离线签单匹配的航班.");
                }
            }
            addDocument.Add("SysBuild", false);
            addDocument.Add("UpdateTime", DateTime.Now);
            addDocument.Add("LastUpdateType", SignatureUpdateType.ManaulOffline);
            addDocument.Add("UserName", userRealName);

            var result = mongoDb.InsertSingleDocument("DataStore", "SignatureStore", addDocument);
            if (result == 1)//离线签单上传成功
            {
                return Request.CreateErrorResponse(HttpStatusCode.OK, ModelState);
            }
            else
            {
                ModelState.AddModelError("err", "离线签单上传失败,无法将签单更新到数据库.");
                return Request.CreateErrorResponse(HttpStatusCode.Accepted, ModelState);
            }
        }
        /// <summary>
        /// 结束签单
        /// </summary>
        /// <param name="model">请求结束签单模型</param>
        /// <returns>返回HTTP返回码,如出错,将同时返回出错信息。<see cref="HttpStatusCode"/></returns>
        [Route("CloseSignature")]
        public HttpResponseMessage CloseSignature(CloseSignatureRequestModel model)
        {
            if (model == null)
            {
                ModelState.AddModelError("err", "参数不能为空.");
                return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
            }
            if (!ModelState.IsValid)
            {
                return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
            }
            var mongoDb = MongoDbInstanceStore.DataStoreInstance;
            var builder = Builders<SignatureReturnModel>.Filter;
            FilterDefinition<SignatureReturnModel> filter;
            filter = builder.Eq(x => x.No, model.No);

            PipelineDefinition<SignatureReturnModel, SignatureReturnModel> pipeline = new BsonDocument[] { };

            #region Project To Combine Auto Data And Manual Data

            ProjectionDefinition<SignatureReturnModel, SignatureReturnModel> project1 = new BsonDocument()
                        .Add("_id", 1.0)
                        .Add("No", 1.0)
                        .Add("Flt", 1.0)
                        .Add("Pnum", 1.0)
                        .Add("Stand", 1.0)
                        .Add("Airline", 1.0)
                        .Add("PlaneType", 1.0)
                        .Add("FType", 1.0)
                        .Add("Pic", 1.0)
                        .Add("SPic", 1.0)
                        .Add("Time", 1.0)
                        .Add("Status", 1.0)
                        .Add("User", 1.0)
                        .Add("Usage", 1.0)
                        .Add("SysBuild", 1.0)
                        .Add("FinalBridgeData", new BsonDocument()
                                .Add("Bridge", new BsonDocument()
                                        .Add("$cond", new BsonDocument()
                                                .Add("if", new BsonDocument()
                                                        .Add("$anyElementTrue", new BsonArray()
                                                                .Add(new BsonArray()
                                                                        .Add("$bridgeData.Bridge")
                                                                        .Add("$AutobridgeData.Bridge")
                                                                )
                                                        )
                                                )
                                                .Add("then", new BsonDocument()
                                                        .Add("beginTime", new BsonDocument()
                                                                .Add("$ifNull", new BsonArray()
                                                                        .Add("$bridgeData.Bridge.beginTime")
                                                                        .Add("$AutobridgeData.Bridge.beginTime")
                                                                )
                                                        )
                                                        .Add("endTime", new BsonDocument()
                                                                .Add("$ifNull", new BsonArray()
                                                                        .Add("$bridgeData.Bridge.endTime")
                                                                        .Add("$AutobridgeData.Bridge.endTime")
                                                                )
                                                        )
                                                        .Add("UseType", new BsonDocument()
                                                                .Add("$ifNull", new BsonArray()
                                                                        .Add("$bridgeData.Bridge.UseType")
                                                                        .Add("$AutobridgeData.Bridge.UseType")
                                                                )
                                                        )
                                                )
                                                .Add("else", BsonNull.Value)
                                        )
                                )
                        )
                        .Add("FinalPcaData", new BsonDocument()
                                .Add("Pca", new BsonDocument()
                                        .Add("$cond", new BsonDocument()
                                                .Add("if", new BsonDocument()
                                                        .Add("$anyElementTrue", new BsonArray()
                                                                .Add(new BsonArray()
                                                                        .Add("$pcaData.Pca")
                                                                        .Add("$AutopcaData.Pca")
                                                                )
                                                        )
                                                )
                                                .Add("then", new BsonDocument()
                                                        .Add("beginTime", new BsonDocument()
                                                                .Add("$ifNull", new BsonArray()
                                                                        .Add("$pcaData.Pca.beginTime")
                                                                        .Add("$AutopcaData.Pca.beginTime")
                                                                )
                                                        )
                                                        .Add("endTime", new BsonDocument()
                                                                .Add("$ifNull", new BsonArray()
                                                                        .Add("$pcaData.Pca.endTime")
                                                                        .Add("$AutopcaData.Pca.endTime")
                                                                )
                                                        )
                                                        .Add("UseType", new BsonDocument()
                                                                .Add("$ifNull", new BsonArray()
                                                                        .Add("$pcaData.Pca.UseType")
                                                                        .Add("$AutopcaData.Pca.UseType")
                                                                )
                                                        )
                                                )
                                                .Add("else", BsonNull.Value)
                                        )
                                )
                        )
                        .Add("FinalAdapterData", new BsonDocument()
                                .Add("Adapter", new BsonDocument()
                                        .Add("$cond", new BsonDocument()
                                                .Add("if", new BsonDocument()
                                                        .Add("$anyElementTrue", new BsonArray()
                                                                .Add(new BsonArray()
                                                                        .Add("$adapterData.Adapter")
                                                                        .Add("$AutoadapterData.Adapter")
                                                                )
                                                        )
                                                )
                                                .Add("then", new BsonDocument()
                                                        .Add("beginTime", new BsonDocument()
                                                                .Add("$ifNull", new BsonArray()
                                                                        .Add("$adapterData.Adapter.beginTime")
                                                                        .Add("$AutoadapterData.Adapter.beginTime")
                                                                )
                                                        )
                                                        .Add("endTime", new BsonDocument()
                                                                .Add("$ifNull", new BsonArray()
                                                                        .Add("$adapterData.Adapter.endTime")
                                                                        .Add("$AutoadapterData.Adapter.endTime")
                                                                )
                                                        )
                                                        .Add("UseType", new BsonDocument()
                                                                .Add("$ifNull", new BsonArray()
                                                                        .Add("$adapterData.Adapter.UseType")
                                                                        .Add("$AutoadapterData.Adapter.UseType")
                                                                )
                                                        )
                                                )
                                                .Add("else", BsonNull.Value)
                                        )
                                )
                        );


            #endregion
            #region Project To Make Final Data

            ProjectionDefinition<SignatureReturnModel, SignatureReturnModel> project2 = new BsonDocument()
                        .Add("_id", 1.0)
                        .Add("No", 1.0)
                        .Add("Flt", 1.0)
                        .Add("Pnum", 1.0)
                        .Add("Stand", 1.0)
                        .Add("Airline", 1.0)
                        .Add("PlaneType", 1.0)
                        .Add("FType", 1.0)
                        .Add("Pic", 1.0)
                        .Add("SPic", 1.0)
                        .Add("Time", 1.0)
                        .Add("Status", 1.0)
                        .Add("User", 1.0)
                        .Add("Usage", 1.0)
                        .Add("SysBuild", 1.0)
                        .Add("bridgeData", new BsonDocument()
                                .Add("Bridge", new BsonDocument()
                                        .Add("$cond", new BsonDocument()
                                                .Add("if", new BsonDocument()
                                                        .Add("$allElementsTrue", new BsonArray()
                                                                .Add(new BsonArray()
                                                                        .Add("$FinalBridgeData.Bridge")
                                                                )
                                                        )
                                                )
                                                .Add("then", new BsonDocument()
                                                        .Add("beginTime", "$FinalBridgeData.Bridge.beginTime")
                                                        .Add("endTime", "$FinalBridgeData.Bridge.endTime")
                                                        .Add("UseType", "$FinalBridgeData.Bridge.UseType")
                                                        .Add("usingTime", new BsonDocument()
                                                                .Add("$cond", new BsonDocument()
                                                                        .Add("if", new BsonDocument()
                                                                                .Add("$allElementsTrue", new BsonArray()
                                                                                        .Add(new BsonArray()
                                                                                                .Add("$FinalBridgeData.Bridge.beginTime")
                                                                                                .Add("$FinalBridgeData.Bridge.endTime")
                                                                                                .Add(new BsonDocument()
                                                                                                        .Add("$gte", new BsonArray()
                                                                                                                .Add("$FinalBridgeData.Bridge.endTime")
                                                                                                                .Add("$FinalBridgeData.Bridge.beginTime")
                                                                                                        )
                                                                                                )
                                                                                        )
                                                                                )
                                                                        )
                                                                        .Add("then", new BsonDocument()
                                                                                .Add("$trunc", new BsonDocument()
                                                                                        .Add("$divide", new BsonArray()
                                                                                                .Add(new BsonDocument()
                                                                                                        .Add("$subtract", new BsonArray()
                                                                                                                .Add("$FinalBridgeData.Bridge.endTime")
                                                                                                                .Add("$FinalBridgeData.Bridge.beginTime")
                                                                                                        )
                                                                                                )
                                                                                                .Add(60000.0)
                                                                                        )
                                                                                )
                                                                        )
                                                                        .Add("else", 0)
                                                                )
                                                        )
                                                )
                                                .Add("else", BsonNull.Value)
                                        )
                                )
                        )
                        .Add("pcaData", new BsonDocument()
                                .Add("Pca", new BsonDocument()
                                        .Add("$cond", new BsonDocument()
                                                .Add("if", new BsonDocument()
                                                        .Add("$allElementsTrue", new BsonArray()
                                                                .Add(new BsonArray()
                                                                        .Add("$FinalPcaData.Pca")
                                                                )
                                                        )
                                                )
                                                .Add("then", new BsonDocument()
                                                        .Add("beginTime", "$FinalPcaData.Pca.beginTime")
                                                        .Add("endTime", "$FinalPcaData.Pca.endTime")
                                                        .Add("UseType", "$FinalPcaData.Pca.UseType")
                                                        .Add("usingTime", new BsonDocument()
                                                                .Add("$cond", new BsonDocument()
                                                                        .Add("if", new BsonDocument()
                                                                                .Add("$allElementsTrue", new BsonArray()
                                                                                        .Add(new BsonArray()
                                                                                                .Add("$FinalPcaData.Pca.beginTime")
                                                                                                .Add("$FinalPcaData.Pca.endTime")
                                                                                                .Add(new BsonDocument()
                                                                                                        .Add("$gte", new BsonArray()
                                                                                                                .Add("$FinalPcaData.Pca.endTime")
                                                                                                                .Add("$FinalPcaData.Pca.beginTime")
                                                                                                        )
                                                                                                )
                                                                                        )
                                                                                )
                                                                        )
                                                                        .Add("then", new BsonDocument()
                                                                                .Add("$trunc", new BsonDocument()
                                                                                        .Add("$divide", new BsonArray()
                                                                                                .Add(new BsonDocument()
                                                                                                        .Add("$subtract", new BsonArray()
                                                                                                                .Add("$FinalPcaData.Pca.endTime")
                                                                                                                .Add("$FinalPcaData.Pca.beginTime")
                                                                                                        )
                                                                                                )
                                                                                                .Add(60000.0)
                                                                                        )
                                                                                )
                                                                        )
                                                                        .Add("else", 0)
                                                                )
                                                        )
                                                )
                                                .Add("else", BsonNull.Value)
                                        )
                                )
                        )
                        .Add("adapterData", new BsonDocument()
                                .Add("Adapter", new BsonDocument()
                                        .Add("$cond", new BsonDocument()
                                                .Add("if", new BsonDocument()
                                                        .Add("$allElementsTrue", new BsonArray()
                                                                .Add(new BsonArray()
                                                                        .Add("$FinalAdapterData.Adapter")
                                                                )
                                                        )
                                                )
                                                .Add("then", new BsonDocument()
                                                        .Add("beginTime", "$FinalAdapterData.Adapter.beginTime")
                                                        .Add("endTime", "$FinalAdapterData.Adapter.endTime")
                                                        .Add("UseType", "$FinalAdapterData.Adapter.UseType")
                                                        .Add("usingTime", new BsonDocument()
                                                                .Add("$cond", new BsonDocument()
                                                                        .Add("if", new BsonDocument()
                                                                                .Add("$allElementsTrue", new BsonArray()
                                                                                        .Add(new BsonArray()
                                                                                                .Add("$FinalAdapterData.Adapter.beginTime")
                                                                                                .Add("$FinalAdapterData.Adapter.endTime")
                                                                                                .Add(new BsonDocument()
                                                                                                        .Add("$gte", new BsonArray()
                                                                                                                .Add("$FinalAdapterData.Adapter.endTime")
                                                                                                                .Add("$FinalAdapterData.Adapter.beginTime")
                                                                                                        )
                                                                                                )
                                                                                        )
                                                                                )
                                                                        )
                                                                        .Add("then", new BsonDocument()
                                                                                .Add("$trunc", new BsonDocument()
                                                                                        .Add("$divide", new BsonArray()
                                                                                                .Add(new BsonDocument()
                                                                                                        .Add("$subtract", new BsonArray()
                                                                                                                .Add("$FinalAdapterData.Adapter.endTime")
                                                                                                                .Add("$FinalAdapterData.Adapter.beginTime")
                                                                                                        )
                                                                                                )
                                                                                                .Add(60000.0)
                                                                                        )
                                                                                )
                                                                        )
                                                                        .Add("else", 0)
                                                                )
                                                        )
                                                )
                                                .Add("else", BsonNull.Value)
                                        )
                                )
                        );


            #endregion

            pipeline = pipeline.Match(filter).Project(project1).Project(project2);
            var result = (mongoDb.GetDataAggregate("DataStore", "SignatureStore", pipeline) as IEnumerable<SignatureReturnModel>)?.ToArray();
            //var result = (mongoDb.GetDataSingel<SignatureReturnModel, SignatureReturnModel>("DataStore", "SignatureStore", filter) as IEnumerable<SignatureReturnModel>)?.ToArray();
            if (result==null)
            {
                ModelState.AddModelError("err", "没有此表单号的数据.");
                return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
            }
            if (result.Length < 1)
            {
                ModelState.AddModelError("err", "没有此表单号的数据.");
                return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
            }
            if (result[0].Status == SignatureStatus.已完结)
            {
                ModelState.AddModelError("err", "签单已完结,请不要重复操作.");
                return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
            }
            var judgeFilled = OtherHelper.IsFilled(result[0].BridgeData, typeof(BridgeData)) & OtherHelper.IsFilled(result[0].PcaData, typeof(PcaData)) & OtherHelper.IsFilled(result[0].AdapterData, typeof(AdapterData));
            //foreach (var item in result[0].PsData)
            //{
            //    judgeFilled &= other_Helper.IsFilled(item, typeof(PassengerStepData));
            //}
            if (judgeFilled == false)
            {
                ModelState.AddModelError("err", "请确认数据填写完整.");
                return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
            }
            var updateBuilder = Builders<SignatureReturnModel>.Update;
            UpdateDefinition<SignatureReturnModel> updateContent;
            updateContent = updateBuilder.Set(x => x.Status, SignatureStatus.已完结);
            var briData = result[0].BridgeData ;
            foreach (PropertyInfo p in briData.GetType().GetProperties())
            {
                if (p.GetValue(briData)!=null)
                {
                    var name = p.Name;
                    var val = p.GetValue(briData) as BridgeData;
                    int usingTime = OtherHelper.CountUsingTime(val.beginTime.Value, val.endTime.Value);
                    if (usingTime<0)
                    {
                        ModelState.AddModelError("err", "请确认"+ "登机桥数据"+"时间填写正确.");
                        return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
                    }
                    updateContent = updateContent.Set("bridgeData."+ name+ ".usingTime", usingTime);
                }
            }
            var pcaData = result[0].PcaData;
            foreach (PropertyInfo p in pcaData.GetType().GetProperties())
            {
                if (p.GetValue(pcaData) != null)
                {
                    var name = p.Name;
                    var val = p.GetValue(pcaData) as PcaData;
                    int usingTime = OtherHelper.CountUsingTime(val.beginTime.Value, val.endTime.Value);
                    if (usingTime < 0)
                    {
                        ModelState.AddModelError("err", "请确认" + "空调数据" + "时间填写正确.");
                        return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
                    }
                    updateContent = updateContent.Set("pcaData." + name + ".usingTime", usingTime);
                }
            }
            var adapterData = result[0].AdapterData;
            foreach (PropertyInfo p in adapterData.GetType().GetProperties())
            {
                if (p.GetValue(adapterData) != null)
                {
                    var name = p.Name;
                    var val = p.GetValue(adapterData) as AdapterData;
                    int usingTime = OtherHelper.CountUsingTime(val.beginTime.Value, val.endTime.Value);
                    if (usingTime < 0)
                    {
                        ModelState.AddModelError("err", "请确认" + "电源数据" + "时间填写正确.");
                        return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
                    }
                    updateContent = updateContent.Set("adapterData." + name + ".usingTime", usingTime);
                }
            }
            //var psData = result[0].PsData;
            //for (int i = 0; i < psData.Length; i++)
            //{
            //    int usingTime = other_Helper.CountUsingTime(psData[i].beginTime.Value, psData[i].endTime.Value);
            //    if (usingTime < 0)
            //    {
            //        ModelState.AddModelError("err", "请确认客梯车第"+i+"项时间填写正确.");
            //        return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
            //    }
            //    updateContent = updateContent.Set("PsData." + i + ".usingTime", usingTime);
            //}
            var updateResult = mongoDb.UpdateSingleDocument("DataStore", "SignatureStore", filter, updateContent);
            if (updateResult >= 1) return new HttpResponseMessage(HttpStatusCode.OK);
            ModelState.AddModelError("err", "更新签单状态失败(LastStep).");
            return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
        }
        /// <summary>
        /// 删除签单
        /// </summary>
        /// <param name="signatureListNo">要删除的签单号</param>
        /// <returns>返回HTTP返回码,如出错,将同时返回出错信息。<see cref="HttpStatusCode"/></returns>
        [Route("DeletedSignatureList")]
        [HttpPost]
        public HttpResponseMessage DeletedSignatureList([FromBody]string signatureListNo)
        {
            var mongoDb = MongoDbInstanceStore.DataStoreInstance;
            var builder = Builders<BsonDocument>.Filter;
            var filter = builder.Eq("No", signatureListNo);
            var resultCount = mongoDb.CountData("DataStore", "SignatureStore", filter);
            if (resultCount<1)
            {
                ModelState.AddModelError("err", "查找不到此单号");
                return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
            }
            var filterDocument = new BsonDocument(new Dictionary<string, object>()
            {
                {"Status",SignatureStatus.已删除}
            });
            var result = mongoDb.UpdateSingleDocument("DataStore", "SignatureStore", filter, filterDocument);
            if (result<1)
            {
                ModelState.AddModelError("err", "删除签单失败");
                return Request.CreateErrorResponse(HttpStatusCode.Accepted, ModelState);
            }
            return Request.CreateResponse(HttpStatusCode.OK);
        }
        /// <summary>
        /// 获取签单列表
        /// </summary>
        /// <param name="model">签单请求模型</param>
        /// <returns>签单列表<see cref="SignatureReturnModel"/></returns>
        [Route("GetSignatureList")]
        public HttpResponseMessage GetSignatureList([FromUri] SignatureRequestModel model)
        {
            var userManager =Request.GetOwinContext().GetUserManager<ApplicationUserManager>();
            var userClaims=userManager.GetClaims(User.Identity.GetUserId());
            string userAirLine = null;
            foreach (var item in userClaims)
            {
                if (item.Type=="UserAirline")
                {
                    userAirLine = item.Value;
                }

            }
            if (!ModelState.IsValid)
            {
                return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
            }
            var mongoDb = MongoDbInstanceStore.DataStoreInstance;
            var builder = Builders<SignatureReturnModel>.Filter;
            FilterDefinition<SignatureReturnModel> filter;
            if (model == null)
            {
                filter = builder.Empty;

            }
            else
            {
                Type modelType = model.GetType();
                PropertyInfo[] propertyList = modelType.GetProperties();
                filter = builder.Empty;
                foreach (PropertyInfo item in propertyList)
                {
                    string name = item.Name;
                    object value = item.GetValue(model);
                    if (value != null&&name!="Prev"&&name!= "Skip"&&name!= "ObjectId" && name!="Flt")
                    {

                        if (name != "Area")
                        {

                            value = value.GetType().IsEnum ? ((int) value).ToString() : value;
                            //builder.Gte(name, value)
                            filter &= value is DateTime ? (model.Prev? builder.Lte(name, value): builder.Gte(name, value)) : value.ToString() == "\"\"" ? builder.Empty : builder.Eq(name, value);
                            //filter &= builder.Eq(name, value);
                        }
                        else
                        {
                            var standArea = new StandArea();
                            var type = standArea.GetType().GetProperty(model.Area.ToString());
                            if (type != null)
                            {
                                var values = type.GetValue(standArea) as IEnumerable<string>;
                                filter &= builder.In(x => x.Stand, values);
                            }
                            else
                            {
                                filter &= builder.In(x => x.Stand, new string[] { });
                            }
                        }
                    }
                }
                if (model.ObjectId != null)
                {
                    filter = model.ObjectId.Aggregate(filter, (current, t) => current & builder.Ne(x => x.Id, t));
                }

                if (model.Flt!=null)
                {
                    filter&= builder.Regex(x => x.Flt, new BsonRegularExpression(".*" + model.Flt + ".*", "i"));
                }
            }
            var softBuilder = Builders<SignatureReturnModel>.Sort;
            var sort = softBuilder.Ascending(x => x.Time).Ascending(x=>x.Id);
            var sortPrev1= softBuilder.Descending(x => x.Time).Descending(x=>x.Id);
            int pageSkip = model?.Skip ?? 0;
            var trueSkip = pageSkip * 20;
            if (userAirLine!=null)
            {
                filter &= builder.Eq("Airline", userAirLine);
            }
            IEnumerable dBdata;
            PipelineDefinition<SignatureReturnModel, SignatureReturnModel> pipeline = new BsonDocument[] { };

            #region Project To Combine Auto Data And Manual Data

            ProjectionDefinition<SignatureReturnModel, SignatureReturnModel> project1 = new BsonDocument()
                        .Add("_id", 1.0)
                        .Add("No", 1.0)
                        .Add("Flt", 1.0)
                        .Add("Pnum", 1.0)
                        .Add("Stand", 1.0)
                        .Add("Airline", 1.0)
                        .Add("PlaneType", 1.0)
                        .Add("FType", 1.0)
                        .Add("Pic", 1.0)
                        .Add("SPic", 1.0)
                        .Add("Time", 1.0)
                        .Add("Status", 1.0)
                        .Add("User", "$RealName")
                        .Add("Usage", 1.0)
                        .Add("psData",1.0)
                        .Add("pbData",1.0)
                        .Add("cbData",1.0)
                        .Add("gData", 1.0)
                        .Add("SysBuild",1.0)
                        .Add("FinalBridgeData", new BsonDocument()
                                .Add("Bridge", new BsonDocument()
                                        .Add("$cond", new BsonDocument()
                                                .Add("if", new BsonDocument()
                                                        .Add("$anyElementTrue", new BsonArray()
                                                                .Add(new BsonArray()
                                                                        .Add("$bridgeData.Bridge")
                                                                        .Add("$AutobridgeData.Bridge")
                                                                )
                                                        )
                                                )
                                                .Add("then", new BsonDocument()
                                                        .Add("beginTime", new BsonDocument()
                                                                .Add("$ifNull", new BsonArray()
                                                                        .Add("$bridgeData.Bridge.beginTime")
                                                                        .Add("$AutobridgeData.Bridge.beginTime")
                                                                )
                                                        )
                                                        .Add("endTime", new BsonDocument()
                                                                .Add("$ifNull", new BsonArray()
                                                                        .Add("$bridgeData.Bridge.endTime")
                                                                        .Add("$AutobridgeData.Bridge.endTime")
                                                                )
                                                        )
                                                        .Add("UseType", new BsonDocument()
                                                                .Add("$ifNull", new BsonArray()
                                                                        .Add("$bridgeData.Bridge.UseType")
                                                                        .Add("$AutobridgeData.Bridge.UseType")
                                                                )
                                                        )
                                                )
                                                .Add("else", BsonNull.Value)
                                        )
                                )
                        )
                        .Add("FinalPcaData", new BsonDocument()
                                .Add("Pca", new BsonDocument()
                                        .Add("$cond", new BsonDocument()
                                                .Add("if", new BsonDocument()
                                                        .Add("$anyElementTrue", new BsonArray()
                                                                .Add(new BsonArray()
                                                                        .Add("$pcaData.Pca")
                                                                        .Add("$AutopcaData.Pca")
                                                                )
                                                        )
                                                )
                                                .Add("then", new BsonDocument()
                                                        .Add("beginTime", new BsonDocument()
                                                                .Add("$ifNull", new BsonArray()
                                                                        .Add("$pcaData.Pca.beginTime")
                                                                        .Add("$AutopcaData.Pca.beginTime")
                                                                )
                                                        )
                                                        .Add("endTime", new BsonDocument()
                                                                .Add("$ifNull", new BsonArray()
                                                                        .Add("$pcaData.Pca.endTime")
                                                                        .Add("$AutopcaData.Pca.endTime")
                                                                )
                                                        )
                                                        .Add("UseType", new BsonDocument()
                                                                .Add("$ifNull", new BsonArray()
                                                                        .Add("$pcaData.Pca.UseType")
                                                                        .Add("$AutopcaData.Pca.UseType")
                                                                )
                                                        )
                                                )
                                                .Add("else", BsonNull.Value)
                                        )
                                )
                        )
                        .Add("FinalAdapterData", new BsonDocument()
                                .Add("Adapter", new BsonDocument()
                                        .Add("$cond", new BsonDocument()
                                                .Add("if", new BsonDocument()
                                                        .Add("$anyElementTrue", new BsonArray()
                                                                .Add(new BsonArray()
                                                                        .Add("$adapterData.Adapter")
                                                                        .Add("$AutoadapterData.Adapter")
                                                                )
                                                        )
                                                )
                                                .Add("then", new BsonDocument()
                                                        .Add("beginTime", new BsonDocument()
                                                                .Add("$ifNull", new BsonArray()
                                                                        .Add("$adapterData.Adapter.beginTime")
                                                                        .Add("$AutoadapterData.Adapter.beginTime")
                                                                )
                                                        )
                                                        .Add("endTime", new BsonDocument()
                                                                .Add("$ifNull", new BsonArray()
                                                                        .Add("$adapterData.Adapter.endTime")
                                                                        .Add("$AutoadapterData.Adapter.endTime")
                                                                )
                                                        )
                                                        .Add("UseType", new BsonDocument()
                                                                .Add("$ifNull", new BsonArray()
                                                                        .Add("$adapterData.Adapter.UseType")
                                                                        .Add("$AutoadapterData.Adapter.UseType")
                                                                )
                                                        )
                                                )
                                                .Add("else", BsonNull.Value)
                                        )
                                )
                        );


            #endregion
            #region Project To Make Final Data

            ProjectionDefinition<SignatureReturnModel, SignatureReturnModel> project2 = new BsonDocument()
                        .Add("_id", 1.0)
                        .Add("No", 1.0)
                        .Add("Flt", 1.0)
                        .Add("Pnum", 1.0)
                        .Add("Stand", 1.0)
                        .Add("Airline", 1.0)
                        .Add("PlaneType", 1.0)
                        .Add("FType", 1.0)
                        .Add("Pic", 1.0)
                        .Add("SPic", 1.0)
                        .Add("Time", 1.0)
                        .Add("Status", 1.0)
                        .Add("User", 1.0)
                        .Add("Usage", 1.0)
                        .Add("SysBuild", 1.0)
                        .Add("psData", 1.0)
                        .Add("pbData", 1.0)
                        .Add("cbData", 1.0)
                        .Add("gData", 1.0)
                        .Add("bridgeData", new BsonDocument()
                                .Add("Bridge", new BsonDocument()
                                        .Add("$cond", new BsonDocument()
                                                .Add("if", new BsonDocument()
                                                        .Add("$allElementsTrue", new BsonArray()
                                                                .Add(new BsonArray()
                                                                        .Add("$FinalBridgeData.Bridge")
                                                                )
                                                        )
                                                )
                                                .Add("then", new BsonDocument()
                                                        .Add("beginTime", "$FinalBridgeData.Bridge.beginTime")
                                                        .Add("endTime", "$FinalBridgeData.Bridge.endTime")
                                                        .Add("UseType", "$FinalBridgeData.Bridge.UseType")
                                                        .Add("usingTime", new BsonDocument()
                                                                .Add("$cond", new BsonDocument()
                                                                        .Add("if", new BsonDocument()
                                                                                .Add("$allElementsTrue", new BsonArray()
                                                                                        .Add(new BsonArray()
                                                                                                .Add("$FinalBridgeData.Bridge.beginTime")
                                                                                                .Add("$FinalBridgeData.Bridge.endTime")
                                                                                                .Add(new BsonDocument()
                                                                                                        .Add("$gte", new BsonArray()
                                                                                                                .Add("$FinalBridgeData.Bridge.endTime")
                                                                                                                .Add("$FinalBridgeData.Bridge.beginTime")
                                                                                                        )
                                                                                                )
                                                                                        )
                                                                                )
                                                                        )
                                                                        .Add("then", new BsonDocument()
                                                                                .Add("$trunc", new BsonDocument()
                                                                                        .Add("$divide", new BsonArray()
                                                                                                .Add(new BsonDocument()
                                                                                                        .Add("$subtract", new BsonArray()
                                                                                                                .Add("$FinalBridgeData.Bridge.endTime")
                                                                                                                .Add("$FinalBridgeData.Bridge.beginTime")
                                                                                                        )
                                                                                                )
                                                                                                .Add(60000.0)
                                                                                        )
                                                                                )
                                                                        )
                                                                        .Add("else", 0)
                                                                )
                                                        )
                                                )
                                                .Add("else", BsonNull.Value)
                                        )
                                )
                        )
                        .Add("pcaData", new BsonDocument()
                                .Add("Pca", new BsonDocument()
                                        .Add("$cond", new BsonDocument()
                                                .Add("if", new BsonDocument()
                                                        .Add("$allElementsTrue", new BsonArray()
                                                                .Add(new BsonArray()
                                                                        .Add("$FinalPcaData.Pca")
                                                                )
                                                        )
                                                )
                                                .Add("then", new BsonDocument()
                                                        .Add("beginTime", "$FinalPcaData.Pca.beginTime")
                                                        .Add("endTime", "$FinalPcaData.Pca.endTime")
                                                        .Add("UseType", "$FinalPcaData.Pca.UseType")
                                                        .Add("usingTime", new BsonDocument()
                                                                .Add("$cond", new BsonDocument()
                                                                        .Add("if", new BsonDocument()
                                                                                .Add("$allElementsTrue", new BsonArray()
                                                                                        .Add(new BsonArray()
                                                                                                .Add("$FinalPcaData.Pca.beginTime")
                                                                                                .Add("$FinalPcaData.Pca.endTime")
                                                                                                .Add(new BsonDocument()
                                                                                                        .Add("$gte", new BsonArray()
                                                                                                                .Add("$FinalPcaData.Pca.endTime")
                                                                                                                .Add("$FinalPcaData.Pca.beginTime")
                                                                                                        )
                                                                                                )
                                                                                        )
                                                                                )
                                                                        )
                                                                        .Add("then", new BsonDocument()
                                                                                .Add("$trunc", new BsonDocument()
                                                                                        .Add("$divide", new BsonArray()
                                                                                                .Add(new BsonDocument()
                                                                                                        .Add("$subtract", new BsonArray()
                                                                                                                .Add("$FinalPcaData.Pca.endTime")
                                                                                                                .Add("$FinalPcaData.Pca.beginTime")
                                                                                                        )
                                                                                                )
                                                                                                .Add(60000.0)
                                                                                        )
                                                                                )
                                                                        )
                                                                        .Add("else", 0)
                                                                )
                                                        )
                                                )
                                                .Add("else", BsonNull.Value)
                                        )
                                )
                        )
                        .Add("adapterData", new BsonDocument()
                                .Add("Adapter", new BsonDocument()
                                        .Add("$cond", new BsonDocument()
                                                .Add("if", new BsonDocument()
                                                        .Add("$allElementsTrue", new BsonArray()
                                                                .Add(new BsonArray()
                                                                        .Add("$FinalAdapterData.Adapter")
                                                                )
                                                        )
                                                )
                                                .Add("then", new BsonDocument()
                                                        .Add("beginTime", "$FinalAdapterData.Adapter.beginTime")
                                                        .Add("endTime", "$FinalAdapterData.Adapter.endTime")
                                                        .Add("UseType", "$FinalAdapterData.Adapter.UseType")
                                                        .Add("usingTime", new BsonDocument()
                                                                .Add("$cond", new BsonDocument()
                                                                        .Add("if", new BsonDocument()
                                                                                .Add("$allElementsTrue", new BsonArray()
                                                                                        .Add(new BsonArray()
                                                                                                .Add("$FinalAdapterData.Adapter.beginTime")
                                                                                                .Add("$FinalAdapterData.Adapter.endTime")
                                                                                                .Add(new BsonDocument()
                                                                                                        .Add("$gte", new BsonArray()
                                                                                                                .Add("$FinalAdapterData.Adapter.endTime")
                                                                                                                .Add("$FinalAdapterData.Adapter.beginTime")
                                                                                                        )
                                                                                                )
                                                                                        )
                                                                                )
                                                                        )
                                                                        .Add("then", new BsonDocument()
                                                                                .Add("$trunc", new BsonDocument()
                                                                                        .Add("$divide", new BsonArray()
                                                                                                .Add(new BsonDocument()
                                                                                                        .Add("$subtract", new BsonArray()
                                                                                                                .Add("$FinalAdapterData.Adapter.endTime")
                                                                                                                .Add("$FinalAdapterData.Adapter.beginTime")
                                                                                                        )
                                                                                                )
                                                                                                .Add(60000.0)
                                                                                        )
                                                                                )
                                                                        )
                                                                        .Add("else", 0)
                                                                )
                                                        )
                                                )
                                                .Add("else", BsonNull.Value)
                                        )
                                )
                        );


            #endregion
            var AbandonedFilter = builder.Or(builder.Eq("abandoned", false), builder.Not(builder.Exists("abandoned")));
            filter = builder.And(filter, AbandonedFilter);
            if (model != null && model.Prev)
            {
                
                pipeline = pipeline.Match(filter).Sort(sortPrev1).Skip(trueSkip).Limit(20).Sort(sort).Project(project1).Project(project2);
                dBdata = mongoDb.GetDataAggregate("DataStore", "SignatureStore", pipeline);
            }
            else
            {
                pipeline = pipeline.Match(filter).Sort(sort).Skip(trueSkip).Limit(20).Project(project1).Project(project2);
                //dBdata = mongoDb.GetDataMany<SignatureReturnModel, SignatureReturnModel>("DataStore", "SignatureStore", filter, sort, trueSkip, 20);
                dBdata = mongoDb.GetDataAggregate("DataStore", "SignatureStore", pipeline);
            }
            return Request.CreateResponse(HttpStatusCode.OK, dBdata);

        }
        /// <summary>
        /// 返回页码数
        /// </summary>
        /// <param name="model">签单请求模型</param>
        /// <returns>返回后10页的数据总数作为分页判断依据</returns>
        [Route("GetSignatureListPageCount")]
        public HttpResponseMessage GetSignatureListPageCount([FromUri] SignatureRequestModel model)
        {
            if (!ModelState.IsValid)
            {
                return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
            }
            var mongoDb = MongoDbInstanceStore.DataStoreInstance;
            var builder = Builders<SignatureReturnModel>.Filter;
            FilterDefinition<SignatureReturnModel> filter;
            if (model == null)
            {
                filter = builder.Empty;

            }
            else
            {
                Type modelType = model.GetType();
                PropertyInfo[] propertyList = modelType.GetProperties();
                filter = builder.Empty;
                foreach (PropertyInfo item in propertyList)
                {
                    string name = item.Name;
                    object value = item.GetValue(model);
                    if (value != null && name != "Prev"&& name !="Skip"&& name != "IsSkip"&&name!= "ObjectId")
                    {

                        if (name != "Area")
                        {

                            value = value.GetType().IsEnum ? ((int)value).ToString() : value;
                            //builder.Gte(name, value)
                            filter &= value is DateTime ? (/*model.Prev ? builder.Lt(name, value) :*/ builder.Gte(name, value)) : value.ToString() == "\"\"" ? builder.Empty : builder.Eq(name, value);
                            //filter &= builder.Eq(name, value);
                        }
                        else
                        {
                            var standArea = new StandArea();
                            var type = standArea.GetType().GetProperty(model.Area.ToString());
                            if (type != null)
                            {
                                var values = type.GetValue(standArea) as IEnumerable<string>;
                                filter &= builder.In(x => x.Stand, values);
                            }
                            else
                            {
                                filter &= builder.In(x => x.Stand, new string[] { });
                            }
                        }
                    }
                }

                if (model.ObjectId!=null)
                {
                    filter = model.ObjectId.Aggregate(filter, (current, t) => current & builder.Ne(x => x.Id, t));
                }
                
            }
            var softBuilder = Builders<SignatureReturnModel>.Sort;
            var sort = softBuilder.Ascending(x => x.Time);
            var dBdata = mongoDb.CountData("DataStore", "SignatureStore", filter, sort, 0, 400);
            var row = new Dictionary<string, int> {{"count", (int) dBdata}};
            return Request.CreateResponse(HttpStatusCode.OK, row);
        }
        /// <summary>
        /// 工作人员在现场通过机位获取特定航班
        /// </summary>
        /// <returns>签单列表<see cref="SignatureReturnModel"/></returns>
        [Route("StaffGetSignatureList")]
        [HttpGet]
        public HttpResponseMessage StaffGetSignatureList([FromUri] StaffSignatureRequsetModel model)
        {
            if (!ModelState.IsValid)
            {
                return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
            }
            var mongoDb = MongoDbInstanceStore.DataStoreInstance;
            var builder = Builders<SignatureReturnModel>.Filter;
            FilterDefinition<SignatureReturnModel> filter;
            if (model==null)
            {
                //filter = builder.Empty;
                filter = builder.And(builder.Gte(x => x.Time, DateTime.Now.AddHours(-10)),
                    builder.Lte(x => x.Time, DateTime.Now.AddHours(10)));
                //filter &= builder.Gte(x => x.Time, DateTime.Now.AddHours(-10));
                //filter &= builder.Lte(x => x.Time, DateTime.Now.AddHours(10));
            }
            else
            {
                
                var StandFilter = model.Stand.IsEmpty() ?  builder.Empty :builder.Eq(x => x.Stand, model.Stand);
                var FltFilter=model.Flt.IsEmpty()?builder.Empty:builder.Regex(x => x.Flt, new BsonRegularExpression(".*" + model.Flt + ".*", "i"));
                FilterDefinition<SignatureReturnModel> AreaFilter;
                if (model.Area != null)
                {
                    var standArea = new StandArea();
                    var type = standArea.GetType().GetProperty(model.Area.ToString());
                    if (type != null)
                    {
                        var values = type.GetValue(standArea) as IEnumerable<string>;
                        AreaFilter = builder.In(x => x.Stand, values);
                    }
                    else
                    {
                        AreaFilter = builder.In(x => x.Stand, new string[] { });
                    }
                }
                else
                {
                    AreaFilter = builder.Empty;
                }
                //var TimeFilter = builder.And(builder.Lte(x => x.Time, DateTime.Now.AddHours(24)));
                filter = builder.And(StandFilter, AreaFilter,FltFilter);
                //if (model.Flt!=null)
                //{
                //    var FltFilter = builder.Regex(x => x.Flt, new BsonRegularExpression(".*" + model.Flt + ".*", "i"));
                //    TimeFilter = builder.And(builder.Lte(x => x.Time, DateTime.Now.AddHours(24)));
                //    filter = builder.And(FltFilter, TimeFilter);
                //}
                
                //filter=builder.And()
            }
            //var stand = model.Stand;
            //var area = model.Area;
            //var flt = model.Flt;
            //filter = builder.Eq(x => x.Stand, model.Stand);
            var softBuilder = Builders<SignatureReturnModel>.Sort;
            var sort = softBuilder.Descending(x => x.Time);
            PipelineDefinition<SignatureReturnModel, SignatureReturnModel> pipeline = new BsonDocument[] { };

            #region Project To Combine Auto Data And Manual Data

            ProjectionDefinition<SignatureReturnModel, SignatureReturnModel> project1 = new BsonDocument()
                        .Add("_id", 1.0)
                        .Add("No", 1.0)
                        .Add("Flt", 1.0)
                        .Add("Pnum", 1.0)
                        .Add("Stand", 1.0)
                        .Add("PlaneType",1.0)
                        .Add("Airline", 1.0)
                        .Add("FType", 1.0)
                        .Add("Pic", 1.0)
                        .Add("SPic", 1.0)
                        .Add("Time", 1.0)
                        .Add("Status", 1.0)
                        .Add("User", "$RealName")
                        .Add("Usage", 1.0)
                        .Add("SysBuild", 1.0)
                        .Add("psData", 1.0)
                        .Add("pbData", 1.0)
                        .Add("cbData", 1.0)
                        .Add("gData", 1.0)
                        .Add("FinalBridgeData", new BsonDocument()
                                .Add("Bridge", new BsonDocument()
                                        .Add("$cond", new BsonDocument()
                                                .Add("if", new BsonDocument()
                                                        .Add("$anyElementTrue", new BsonArray()
                                                                .Add(new BsonArray()
                                                                        .Add("$bridgeData.Bridge")
                                                                        .Add("$AutobridgeData.Bridge")
                                                                )
                                                        )
                                                )
                                                .Add("then", new BsonDocument()
                                                        .Add("beginTime", new BsonDocument()
                                                                .Add("$ifNull", new BsonArray()
                                                                        .Add("$bridgeData.Bridge.beginTime")
                                                                        .Add("$AutobridgeData.Bridge.beginTime")
                                                                )
                                                        )
                                                        .Add("endTime", new BsonDocument()
                                                                .Add("$ifNull", new BsonArray()
                                                                        .Add("$bridgeData.Bridge.endTime")
                                                                        .Add("$AutobridgeData.Bridge.endTime")
                                                                )
                                                        )
                                                        .Add("UseType", new BsonDocument()
                                                                .Add("$ifNull", new BsonArray()
                                                                        .Add("$bridgeData.Bridge.UseType")
                                                                        .Add("$AutobridgeData.Bridge.UseType")
                                                                )
                                                        )
                                                )
                                                .Add("else", BsonNull.Value)
                                        )
                                )
                        )
                        .Add("FinalPcaData", new BsonDocument()
                                .Add("Pca", new BsonDocument()
                                        .Add("$cond", new BsonDocument()
                                                .Add("if", new BsonDocument()
                                                        .Add("$anyElementTrue", new BsonArray()
                                                                .Add(new BsonArray()
                                                                        .Add("$pcaData.Pca")
                                                                        .Add("$AutopcaData.Pca")
                                                                )
                                                        )
                                                )
                                                .Add("then", new BsonDocument()
                                                        .Add("beginTime", new BsonDocument()
                                                                .Add("$ifNull", new BsonArray()
                                                                        .Add("$pcaData.Pca.beginTime")
                                                                        .Add("$AutopcaData.Pca.beginTime")
                                                                )
                                                        )
                                                        .Add("endTime", new BsonDocument()
                                                                .Add("$ifNull", new BsonArray()
                                                                        .Add("$pcaData.Pca.endTime")
                                                                        .Add("$AutopcaData.Pca.endTime")
                                                                )
                                                        )
                                                        .Add("UseType", new BsonDocument()
                                                                .Add("$ifNull", new BsonArray()
                                                                        .Add("$pcaData.Pca.UseType")
                                                                        .Add("$AutopcaData.Pca.UseType")
                                                                )
                                                        )
                                                )
                                                .Add("else", BsonNull.Value)
                                        )
                                )
                        )
                        .Add("FinalAdapterData", new BsonDocument()
                                .Add("Adapter", new BsonDocument()
                                        .Add("$cond", new BsonDocument()
                                                .Add("if", new BsonDocument()
                                                        .Add("$anyElementTrue", new BsonArray()
                                                                .Add(new BsonArray()
                                                                        .Add("$adapterData.Adapter")
                                                                        .Add("$AutoadapterData.Adapter")
                                                                )
                                                        )
                                                )
                                                .Add("then", new BsonDocument()
                                                        .Add("beginTime", new BsonDocument()
                                                                .Add("$ifNull", new BsonArray()
                                                                        .Add("$adapterData.Adapter.beginTime")
                                                                        .Add("$AutoadapterData.Adapter.beginTime")
                                                                )
                                                        )
                                                        .Add("endTime", new BsonDocument()
                                                                .Add("$ifNull", new BsonArray()
                                                                        .Add("$adapterData.Adapter.endTime")
                                                                        .Add("$AutoadapterData.Adapter.endTime")
                                                                )
                                                        )
                                                        .Add("UseType", new BsonDocument()
                                                                .Add("$ifNull", new BsonArray()
                                                                        .Add("$adapterData.Adapter.UseType")
                                                                        .Add("$AutoadapterData.Adapter.UseType")
                                                                )
                                                        )
                                                )
                                                .Add("else", BsonNull.Value)
                                        )
                                )
                        );


            #endregion
            #region Project To Make Final Data

            ProjectionDefinition<SignatureReturnModel, SignatureReturnModel> project2 = new BsonDocument()
                        .Add("_id", 1.0)
                        .Add("No", 1.0)
                        .Add("Flt", 1.0)
                        .Add("Pnum", 1.0)
                        .Add("Stand", 1.0)
                        .Add("PlaneType", 1.0)
                        .Add("Airline", 1.0)
                        .Add("FType", 1.0)
                        .Add("Pic", 1.0)
                        .Add("SPic", 1.0)
                        .Add("Time", 1.0)
                        .Add("Status", 1.0)
                        .Add("User", 1.0)
                        .Add("Usage", 1.0)
                        .Add("SysBuild", 1.0)
                        .Add("psData", 1.0)
                        .Add("pbData", 1.0)
                        .Add("cbData", 1.0)
                        .Add("gData", 1.0)
                        .Add("bridgeData", new BsonDocument()
                                .Add("Bridge", new BsonDocument()
                                        .Add("$cond", new BsonDocument()
                                                .Add("if", new BsonDocument()
                                                        .Add("$allElementsTrue", new BsonArray()
                                                                .Add(new BsonArray()
                                                                        .Add("$FinalBridgeData.Bridge")
                                                                )
                                                        )
                                                )
                                                .Add("then", new BsonDocument()
                                                        .Add("beginTime", "$FinalBridgeData.Bridge.beginTime")
                                                        .Add("endTime", "$FinalBridgeData.Bridge.endTime")
                                                        .Add("UseType", "$FinalBridgeData.Bridge.UseType")
                                                        .Add("usingTime", new BsonDocument()
                                                                .Add("$cond", new BsonDocument()
                                                                        .Add("if", new BsonDocument()
                                                                                .Add("$allElementsTrue", new BsonArray()
                                                                                        .Add(new BsonArray()
                                                                                                .Add("$FinalBridgeData.Bridge.beginTime")
                                                                                                .Add("$FinalBridgeData.Bridge.endTime")
                                                                                                .Add(new BsonDocument()
                                                                                                        .Add("$gte", new BsonArray()
                                                                                                                .Add("$FinalBridgeData.Bridge.endTime")
                                                                                                                .Add("$FinalBridgeData.Bridge.beginTime")
                                                                                                        )
                                                                                                )
                                                                                        )
                                                                                )
                                                                        )
                                                                        .Add("then", new BsonDocument()
                                                                                .Add("$trunc", new BsonDocument()
                                                                                        .Add("$divide", new BsonArray()
                                                                                                .Add(new BsonDocument()
                                                                                                        .Add("$subtract", new BsonArray()
                                                                                                                .Add("$FinalBridgeData.Bridge.endTime")
                                                                                                                .Add("$FinalBridgeData.Bridge.beginTime")
                                                                                                        )
                                                                                                )
                                                                                                .Add(60000.0)
                                                                                        )
                                                                                )
                                                                        )
                                                                        .Add("else", 0)
                                                                )
                                                        )
                                                )
                                                .Add("else", BsonNull.Value)
                                        )
                                )
                        )
                        .Add("pcaData", new BsonDocument()
                                .Add("Pca", new BsonDocument()
                                        .Add("$cond", new BsonDocument()
                                                .Add("if", new BsonDocument()
                                                        .Add("$allElementsTrue", new BsonArray()
                                                                .Add(new BsonArray()
                                                                        .Add("$FinalPcaData.Pca")
                                                                )
                                                        )
                                                )
                                                .Add("then", new BsonDocument()
                                                        .Add("beginTime", "$FinalPcaData.Pca.beginTime")
                                                        .Add("endTime", "$FinalPcaData.Pca.endTime")
                                                        .Add("UseType", "$FinalPcaData.Pca.UseType")
                                                        .Add("usingTime", new BsonDocument()
                                                                .Add("$cond", new BsonDocument()
                                                                        .Add("if", new BsonDocument()
                                                                                .Add("$allElementsTrue", new BsonArray()
                                                                                        .Add(new BsonArray()
                                                                                                .Add("$FinalPcaData.Pca.beginTime")
                                                                                                .Add("$FinalPcaData.Pca.endTime")
                                                                                                .Add(new BsonDocument()
                                                                                                        .Add("$gte", new BsonArray()
                                                                                                                .Add("$FinalPcaData.Pca.endTime")
                                                                                                                .Add("$FinalPcaData.Pca.beginTime")
                                                                                                        )
                                                                                                )
                                                                                        )
                                                                                )
                                                                        )
                                                                        .Add("then", new BsonDocument()
                                                                                .Add("$trunc", new BsonDocument()
                                                                                        .Add("$divide", new BsonArray()
                                                                                                .Add(new BsonDocument()
                                                                                                        .Add("$subtract", new BsonArray()
                                                                                                                .Add("$FinalPcaData.Pca.endTime")
                                                                                                                .Add("$FinalPcaData.Pca.beginTime")
                                                                                                        )
                                                                                                )
                                                                                                .Add(60000.0)
                                                                                        )
                                                                                )
                                                                        )
                                                                        .Add("else", 0)
                                                                )
                                                        )
                                                )
                                                .Add("else", BsonNull.Value)
                                        )
                                )
                        )
                        .Add("adapterData", new BsonDocument()
                                .Add("Adapter", new BsonDocument()
                                        .Add("$cond", new BsonDocument()
                                                .Add("if", new BsonDocument()
                                                        .Add("$allElementsTrue", new BsonArray()
                                                                .Add(new BsonArray()
                                                                        .Add("$FinalAdapterData.Adapter")
                                                                )
                                                        )
                                                )
                                                .Add("then", new BsonDocument()
                                                        .Add("beginTime", "$FinalAdapterData.Adapter.beginTime")
                                                        .Add("endTime", "$FinalAdapterData.Adapter.endTime")
                                                        .Add("UseType", "$FinalAdapterData.Adapter.UseType")
                                                        .Add("usingTime", new BsonDocument()
                                                                .Add("$cond", new BsonDocument()
                                                                        .Add("if", new BsonDocument()
                                                                                .Add("$allElementsTrue", new BsonArray()
                                                                                        .Add(new BsonArray()
                                                                                                .Add("$FinalAdapterData.Adapter.beginTime")
                                                                                                .Add("$FinalAdapterData.Adapter.endTime")
                                                                                                .Add(new BsonDocument()
                                                                                                        .Add("$gte", new BsonArray()
                                                                                                                .Add("$FinalAdapterData.Adapter.endTime")
                                                                                                                .Add("$FinalAdapterData.Adapter.beginTime")
                                                                                                        )
                                                                                                )
                                                                                        )
                                                                                )
                                                                        )
                                                                        .Add("then", new BsonDocument()
                                                                                .Add("$trunc", new BsonDocument()
                                                                                        .Add("$divide", new BsonArray()
                                                                                                .Add(new BsonDocument()
                                                                                                        .Add("$subtract", new BsonArray()
                                                                                                                .Add("$FinalAdapterData.Adapter.endTime")
                                                                                                                .Add("$FinalAdapterData.Adapter.beginTime")
                                                                                                        )
                                                                                                )
                                                                                                .Add(60000.0)
                                                                                        )
                                                                                )
                                                                        )
                                                                        .Add("else", 0)
                                                                )
                                                        )
                                                )
                                                .Add("else", BsonNull.Value)
                                        )
                                )
                        );


            #endregion
            var AbandonedFilter = builder.Or(builder.Eq("abandoned", false), builder.Not(builder.Exists("abandoned")));
            filter = builder.And(filter, AbandonedFilter);
            pipeline = pipeline.Match(filter).Sort(sort).Limit(40).Project(project1).Project(project2);
            //var dBdata = mongoDb.GetDataMany<SignatureReturnModel, SignatureReturnModel>("DataStore", "SignatureStore", filter, sort, 0, 40);
            var dBdata = mongoDb.GetDataAggregate("DataStore", "SignatureStore",
                pipeline);
            return Request.CreateResponse(HttpStatusCode.OK, dBdata);
        }
        /// <summary>
        /// 导出签单列表(数据为查询时间一个月内)
        /// </summary>
        /// <param name="model"></param>
        /// <returns>返回Excel文档</returns>
        [Route("ExportSignatureList")]
        [HttpGet]
        public IEnumerable<SignatureExcelModel> ExportSignatureList([FromUri] SignatureExportRequestModel model)
        {

             if (!ModelState.IsValid || model == null)
            {
                throw new Exception("导出Excel请求参数不正确.");
            }

            var mongoDb = MongoDbInstanceStore.DataStoreInstance;
            var builder = Builders<BsonDocument>.Filter;
            FilterDefinition<BsonDocument> filter = builder.Empty;

            FilterDefinition<BsonDocument> TimeFilter;
            FilterDefinition<BsonDocument> AreaFilter;
            if (model.Mode == ExportMode.range)
            {
                var rangeFilter1 = builder.Gte("Time", model.Range[0]);
                var rangeFilter2 = builder.Lte("Time", model.Range[1]);
                TimeFilter = builder.And(rangeFilter1, rangeFilter2);
            }
            else if (model.Mode == ExportMode.month)
            {
                var monthFilter1 = builder.Gte("Time", model.Month);
                var monthFilter2 = builder.Lte("Time", model.Month.AddMonths(1));
                TimeFilter = builder.And(monthFilter1, monthFilter2);
            }
            else
            {
                TimeFilter = builder.And(builder.Gte("Time", DateTime.Now),builder.Lte("Time",DateTime.Now));
            }

            var FltFilter= model.Flt.IsEmpty() ? builder.Empty: builder.Regex("Flt", new BsonRegularExpression(".*" + model.Flt + ".*", "i"));
            var StandFilter =model.Stand.IsEmpty() ? builder.Empty : builder.Eq("Stand", model.Stand);
            var AirlineFilter = model.Airline.IsEmpty()? builder.Empty : builder.Eq("Airline", model.Airline);
            var Status = model.Status.HasValue? builder.Eq("Stauts", (int)model.Status):builder.Empty;
            var FTypeFilter = model.FType.HasValue? builder.Eq("FType", (int) model.FType): builder.Empty;
            var PlaneTypeFilter=model.PlaneType.IsEmpty()? builder.Empty : builder.Eq("PlaneType", model.PlaneType);
            var PnumFilter = model.Pnum.IsEmpty() ? builder.Empty : builder.Eq("Pnum", model.Pnum);
            var UserNameFilter = model.UserName.IsEmpty()? builder.Empty: builder.Eq("UserName", model.UserName);
            var STypeFilter = model.SType.HasValue ? builder.Eq("SType", (int)model.SType) : builder.Empty;
            var AbandonedFilter = builder.Or(builder.Eq("abandoned", false), builder.Not(builder.Exists("abandoned")));
            //筛选区域
            var standArea = new StandArea();
            var type = standArea.GetType().GetProperty(model.Area.ToString());
            if (type != null)
            {
                var values = type.GetValue(standArea) as IEnumerable<string>;
                AreaFilter = builder.In("Stand", values);
            }
            else
            {
                AreaFilter = builder.Empty;
            }

            filter = builder.And(TimeFilter,FltFilter, StandFilter, AirlineFilter, Status, FTypeFilter, PlaneTypeFilter,
                PnumFilter, UserNameFilter, STypeFilter, AreaFilter,AbandonedFilter);
            {
                //Type modelType = model.GetType();
                //PropertyInfo[] propertyList = modelType.GetProperties();
                //filter = builder.Empty;
                //foreach (PropertyInfo item in propertyList)
                //{
                //    string name = item.Name;
                //    object value = item.GetValue(model);
                //    if (value != null && name != "Prev" && name != "Skip" && name != "IsSkip" && name != "ObjectId")
                //    {

                //        if (name != "Area")
                //        {

                //            value = value.GetType().IsEnum ? ((int)value).ToString() : value;
                //            filter &= value is DateTime ? builder.Gte(name, value) : value.ToString() == "\"\"" ? builder.Empty : builder.Eq(name, value);
                //        }
                //        else
                //        {
                //            var standArea = new StandArea();
                //            var type = standArea.GetType().GetProperty(model.Area.ToString());
                //            if (type != null)
                //            {
                //                var values = type.GetValue(standArea) as IEnumerable<string>;
                //                filter &= builder.In("Stand", values);
                //            }
                //            else
                //            {
                //                filter &= builder.In("Stand", new string[] { });
                //            }
                //        }
                //    }
                //}

                //filter &= builder.Ne("Status", SignatureStatus.已删除);//状态不在完成的(测试时不加入0 1)
                //filter &= builder.Ne("Status", SignatureStatus.已创建);//状态不在完成的(测试时不加入0 1)
                //filter &= builder.Eq("Status", SignatureStatus.已完结);
            }
            var softBuilder = Builders<BsonDocument>.Sort;
            var sort = softBuilder.Ascending("Time");
            PipelineDefinition<BsonDocument, BsonDocument> pipeline = new BsonDocument[]
            {
                //new BsonDocument("$addFields", new BsonDocument()
                //    .Add("BridgeBeginTime", "$bridgeData.Bridge.beginTime")
                //    .Add("BridgeEndTime", "$bridgeData.Bridge.endTime")
                //    .Add("BridgeUseType", "$bridgeData.Bridge.UseType")
                //    .Add("BridgeUsingTime", "$bridgeData.Bridge.usingTime")
                //    .Add("PcaBeginTime", "$pcaData.Pca.beginTime")
                //    .Add("PcaEndTime", "$pcaData.Pca.endTime")
                //    .Add("PcaUseType", "$pcaData.Pca.UseType")
                //    .Add("PcaUsingTime", "$pcaData.Pca.usingTime")
                //    .Add("AdapterBeginTime", "$adapterData.Adapter.beginTime")
                //    .Add("AdapterEndTime", "$adapterData.Adapter.endTime")
                //    .Add("AdapterUseType", "$adapterData.Adapter.UseType")
                //    .Add("AdapterUsingTime", "$adapterData.Adapter.usingTime"))
                    //.Add("PsBeginTime", new BsonDocument()
                    //    .Add("$arrayElemAt", new BsonArray()
                    //        .Add("$PsData")
                    //        .Add(0.0)
                    //    )
                    //)
                    //.Add("PsEndTime", new BsonDocument()
                    //    .Add("$arrayElemAt", new BsonArray()
                    //        .Add("$PsData")
                    //        .Add(0.0)
                    //    )
                    //)
                    //.Add("PsUseType", new BsonDocument()
                    //    .Add("$arrayElemAt", new BsonArray()
                    //        .Add("$PsData")
                    //        .Add(0.0)
                    //    )
                    //)
                    //.Add("PsUsingTime", new BsonDocument()
                    //    .Add("$arrayElemAt", new BsonArray()
                    //        .Add("$PsData")
                    //        .Add(0.0)
                    //    )
                    //))
            };

            #region Project To Combine Auto Data And Manual Data

            ProjectionDefinition<BsonDocument, BsonDocument> project1 = new BsonDocument()
                        .Add("_id", 1.0)
                        .Add("No", 1.0)
                        .Add("Flt", 1.0)
                        .Add("Pnum", 1.0)
                        .Add("Stand", 1.0)
                        .Add("Airline", 1.0)
                        .Add("FType", 1.0)
                        .Add("Pic", 1.0)
                        .Add("SPic", 1.0)
                        .Add("Time", 1.0)
                        .Add("Status", 1.0)
                        .Add("User", 1.0)
                        .Add("Usage", 1.0)
                        .Add("psData", 1.0)
                        .Add("pbData", 1.0)
                        .Add("cbData", 1.0)
                        .Add("gData", 1.0)
                        .Add("FinalBridgeData", new BsonDocument()
                                .Add("Bridge", new BsonDocument()
                                        .Add("$cond", new BsonDocument()
                                                .Add("if", new BsonDocument()
                                                        .Add("$anyElementTrue", new BsonArray()
                                                                .Add(new BsonArray()
                                                                        .Add("$bridgeData.Bridge")
                                                                        .Add("$AutobridgeData.Bridge")
                                                                )
                                                        )
                                                )
                                                .Add("then", new BsonDocument()
                                                        .Add("beginTime", new BsonDocument()
                                                                .Add("$ifNull", new BsonArray()
                                                                        .Add("$bridgeData.Bridge.beginTime")
                                                                        .Add("$AutobridgeData.Bridge.beginTime")
                                                                )
                                                        )
                                                        .Add("endTime", new BsonDocument()
                                                                .Add("$ifNull", new BsonArray()
                                                                        .Add("$bridgeData.Bridge.endTime")
                                                                        .Add("$AutobridgeData.Bridge.endTime")
                                                                )
                                                        )
                                                        .Add("UseType", new BsonDocument()
                                                                .Add("$ifNull", new BsonArray()
                                                                        .Add("$bridgeData.Bridge.UseType")
                                                                        .Add("$AutobridgeData.Bridge.UseType")
                                                                )
                                                        )
                                                )
                                                .Add("else", BsonNull.Value)
                                        )
                                )
                        )
                        .Add("FinalPcaData", new BsonDocument()
                                .Add("Pca", new BsonDocument()
                                        .Add("$cond", new BsonDocument()
                                                .Add("if", new BsonDocument()
                                                        .Add("$anyElementTrue", new BsonArray()
                                                                .Add(new BsonArray()
                                                                        .Add("$pcaData.Pca")
                                                                        .Add("$AutopcaData.Pca")
                                                                )
                                                        )
                                                )
                                                .Add("then", new BsonDocument()
                                                        .Add("beginTime", new BsonDocument()
                                                                .Add("$ifNull", new BsonArray()
                                                                        .Add("$pcaData.Pca.beginTime")
                                                                        .Add("$AutopcaData.Pca.beginTime")
                                                                )
                                                        )
                                                        .Add("endTime", new BsonDocument()
                                                                .Add("$ifNull", new BsonArray()
                                                                        .Add("$pcaData.Pca.endTime")
                                                                        .Add("$AutopcaData.Pca.endTime")
                                                                )
                                                        )
                                                        .Add("UseType", new BsonDocument()
                                                                .Add("$ifNull", new BsonArray()
                                                                        .Add("$pcaData.Pca.UseType")
                                                                        .Add("$AutopcaData.Pca.UseType")
                                                                )
                                                        )
                                                )
                                                .Add("else", BsonNull.Value)
                                        )
                                )
                        )
                        .Add("FinalAdapterData", new BsonDocument()
                                .Add("Adapter", new BsonDocument()
                                        .Add("$cond", new BsonDocument()
                                                .Add("if", new BsonDocument()
                                                        .Add("$anyElementTrue", new BsonArray()
                                                                .Add(new BsonArray()
                                                                        .Add("$adapterData.Adapter")
                                                                        .Add("$AutoadapterData.Adapter")
                                                                )
                                                        )
                                                )
                                                .Add("then", new BsonDocument()
                                                        .Add("beginTime", new BsonDocument()
                                                                .Add("$ifNull", new BsonArray()
                                                                        .Add("$adapterData.Adapter.beginTime")
                                                                        .Add("$AutoadapterData.Adapter.beginTime")
                                                                )
                                                        )
                                                        .Add("endTime", new BsonDocument()
                                                                .Add("$ifNull", new BsonArray()
                                                                        .Add("$adapterData.Adapter.endTime")
                                                                        .Add("$AutoadapterData.Adapter.endTime")
                                                                )
                                                        )
                                                        .Add("UseType", new BsonDocument()
                                                                .Add("$ifNull", new BsonArray()
                                                                        .Add("$adapterData.Adapter.UseType")
                                                                        .Add("$AutoadapterData.Adapter.UseType")
                                                                )
                                                        )
                                                )
                                                .Add("else", BsonNull.Value)
                                        )
                                )
                        );


            #endregion
            #region Project To Make Final Data

            ProjectionDefinition<BsonDocument, BsonDocument> project2 = new BsonDocument()
                        .Add("_id", 1.0)
                        .Add("No", 1.0)
                        .Add("Flt", 1.0)
                        .Add("Pnum", 1.0)
                        .Add("Stand", 1.0)
                        .Add("Airline", 1.0)
                        .Add("FType", 1.0)
                        .Add("Pic", 1.0)
                        .Add("SPic", 1.0)
                        .Add("Time", 1.0)
                        .Add("Status", 1.0)
                        .Add("User", 1.0)
                        .Add("Usage", 1.0)
                        .Add("psData", 1.0)
                        .Add("pbData", 1.0)
                        .Add("cbData", 1.0)
                        .Add("gData", 1.0)
                        .Add("bridgeData", new BsonDocument()
                                .Add("Bridge", new BsonDocument()
                                        .Add("$cond", new BsonDocument()
                                                .Add("if", new BsonDocument()
                                                        .Add("$allElementsTrue", new BsonArray()
                                                                .Add(new BsonArray()
                                                                        .Add("$FinalBridgeData.Bridge")
                                                                )
                                                        )
                                                )
                                                .Add("then", new BsonDocument()
                                                        .Add("beginTime", "$FinalBridgeData.Bridge.beginTime")
                                                        .Add("endTime", "$FinalBridgeData.Bridge.endTime")
                                                        .Add("UseType", "$FinalBridgeData.Bridge.UseType")
                                                        .Add("usingTime", new BsonDocument()
                                                                .Add("$cond", new BsonDocument()
                                                                        .Add("if", new BsonDocument()
                                                                                .Add("$allElementsTrue", new BsonArray()
                                                                                        .Add(new BsonArray()
                                                                                                .Add("$FinalBridgeData.Bridge.beginTime")
                                                                                                .Add("$FinalBridgeData.Bridge.endTime")
                                                                                                .Add(new BsonDocument()
                                                                                                        .Add("$gte", new BsonArray()
                                                                                                                .Add("$FinalBridgeData.Bridge.endTime")
                                                                                                                .Add("$FinalBridgeData.Bridge.beginTime")
                                                                                                        )
                                                                                                )
                                                                                        )
                                                                                )
                                                                        )
                                                                        .Add("then", new BsonDocument()
                                                                                .Add("$trunc", new BsonDocument()
                                                                                        .Add("$divide", new BsonArray()
                                                                                                .Add(new BsonDocument()
                                                                                                        .Add("$subtract", new BsonArray()
                                                                                                                .Add("$FinalBridgeData.Bridge.endTime")
                                                                                                                .Add("$FinalBridgeData.Bridge.beginTime")
                                                                                                        )
                                                                                                )
                                                                                                .Add(60000.0)
                                                                                        )
                                                                                )
                                                                        )
                                                                        .Add("else", 0)
                                                                )
                                                        )
                                                )
                                                .Add("else", BsonNull.Value)
                                        )
                                )
                        )
                        .Add("pcaData", new BsonDocument()
                                .Add("Pca", new BsonDocument()
                                        .Add("$cond", new BsonDocument()
                                                .Add("if", new BsonDocument()
                                                        .Add("$allElementsTrue", new BsonArray()
                                                                .Add(new BsonArray()
                                                                        .Add("$FinalPcaData.Pca")
                                                                )
                                                        )
                                                )
                                                .Add("then", new BsonDocument()
                                                        .Add("beginTime", "$FinalPcaData.Pca.beginTime")
                                                        .Add("endTime", "$FinalPcaData.Pca.endTime")
                                                        .Add("UseType", "$FinalPcaData.Pca.UseType")
                                                        .Add("usingTime", new BsonDocument()
                                                                .Add("$cond", new BsonDocument()
                                                                        .Add("if", new BsonDocument()
                                                                                .Add("$allElementsTrue", new BsonArray()
                                                                                        .Add(new BsonArray()
                                                                                                .Add("$FinalPcaData.Pca.beginTime")
                                                                                                .Add("$FinalPcaData.Pca.endTime")
                                                                                                .Add(new BsonDocument()
                                                                                                        .Add("$gte", new BsonArray()
                                                                                                                .Add("$FinalPcaData.Pca.endTime")
                                                                                                                .Add("$FinalPcaData.Pca.beginTime")
                                                                                                        )
                                                                                                )
                                                                                        )
                                                                                )
                                                                        )
                                                                        .Add("then", new BsonDocument()
                                                                                .Add("$trunc", new BsonDocument()
                                                                                        .Add("$divide", new BsonArray()
                                                                                                .Add(new BsonDocument()
                                                                                                        .Add("$subtract", new BsonArray()
                                                                                                                .Add("$FinalPcaData.Pca.endTime")
                                                                                                                .Add("$FinalPcaData.Pca.beginTime")
                                                                                                        )
                                                                                                )
                                                                                                .Add(60000.0)
                                                                                        )
                                                                                )
                                                                        )
                                                                        .Add("else", 0)
                                                                )
                                                        )
                                                )
                                                .Add("else", BsonNull.Value)
                                        )
                                )
                        )
                        .Add("adapterData", new BsonDocument()
                                .Add("Adapter", new BsonDocument()
                                        .Add("$cond", new BsonDocument()
                                                .Add("if", new BsonDocument()
                                                        .Add("$allElementsTrue", new BsonArray()
                                                                .Add(new BsonArray()
                                                                        .Add("$FinalAdapterData.Adapter")
                                                                )
                                                        )
                                                )
                                                .Add("then", new BsonDocument()
                                                        .Add("beginTime", "$FinalAdapterData.Adapter.beginTime")
                                                        .Add("endTime", "$FinalAdapterData.Adapter.endTime")
                                                        .Add("UseType", "$FinalAdapterData.Adapter.UseType")
                                                        .Add("usingTime", new BsonDocument()
                                                                .Add("$cond", new BsonDocument()
                                                                        .Add("if", new BsonDocument()
                                                                                .Add("$allElementsTrue", new BsonArray()
                                                                                        .Add(new BsonArray()
                                                                                                .Add("$FinalAdapterData.Adapter.beginTime")
                                                                                                .Add("$FinalAdapterData.Adapter.endTime")
                                                                                                .Add(new BsonDocument()
                                                                                                        .Add("$gte", new BsonArray()
                                                                                                                .Add("$FinalAdapterData.Adapter.endTime")
                                                                                                                .Add("$FinalAdapterData.Adapter.beginTime")
                                                                                                        )
                                                                                                )
                                                                                        )
                                                                                )
                                                                        )
                                                                        .Add("then", new BsonDocument()
                                                                                .Add("$trunc", new BsonDocument()
                                                                                        .Add("$divide", new BsonArray()
                                                                                                .Add(new BsonDocument()
                                                                                                        .Add("$subtract", new BsonArray()
                                                                                                                .Add("$FinalAdapterData.Adapter.endTime")
                                                                                                                .Add("$FinalAdapterData.Adapter.beginTime")
                                                                                                        )
                                                                                                )
                                                                                                .Add(60000.0)
                                                                                        )
                                                                                )
                                                                        )
                                                                        .Add("else", 0)
                                                                )
                                                        )
                                                )
                                                .Add("else", BsonNull.Value)
                                        )
                                )
                        );


            #endregion
            #region Project To Make Correct Format

            ProjectionDefinition<BsonDocument, SignatureExcelModel> project3 = new BsonDocument()
                .Add("No", 1.0)
                .Add("Flt", 1.0)
                .Add("Pnum", 1.0)
                .Add("Stand", 1.0)
                .Add("Airline", 1.0)
                .Add("FType", 1.0)
                .Add("Time", 1.0)
                .Add("Usage", 1.0)
                .Add("psData", 1.0)
                .Add("pbData", 1.0)
                .Add("cbData", 1.0)
                .Add("gData", 1.0)
                .Add("BridgeBeginTime", "$bridgeData.Bridge.beginTime")
                .Add("BridgeEndTime", "$bridgeData.Bridge.endTime")
                .Add("BridgeUseType", "$bridgeData.Bridge.UseType")
                .Add("BridgeUsingTime", "$bridgeData.Bridge.usingTime")
                .Add("PcaBeginTime", "$pcaData.Pca.beginTime")
                .Add("PcaEndTime", "$pcaData.Pca.endTime")
                .Add("PcaUseType", "$pcaData.Pca.UseType")
                .Add("PcaUsingTime", "$pcaData.Pca.usingTime")
                .Add("AdapterBeginTime", "$adapterData.Adapter.beginTime")
                .Add("AdapterEndTime", "$adapterData.Adapter.endTime")
                .Add("AdapterUseType", "$adapterData.Adapter.UseType")
                .Add("AdapterUsingTime", "$adapterData.Adapter.usingTime");

            #endregion

           var pipelineNew =pipeline.Match(filter).Sort(sort).Project(project1).Project(project2).Project(project3);
            IEnumerable<SignatureExcelModel> dBdata;
            try
            {
                 dBdata =   mongoDb.GetDataAggregate("DataStore", "SignatureStore", pipelineNew) as IEnumerable<SignatureExcelModel>;
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                throw;
            }
            
            // var dBdata = mongoDb.GetDataAggregate("DataStore", "SignatureStore", pipeline) as IEnumerable<SignatureExcelModel>; 
           //var dBdata = mongoDb.GetDataMany<BsonDocument, SignatureExcelModel>("DataStore", "SignatureStore", filter,sort, 0, 0, projection);
            return dBdata;
        }
        [Route("ExtraExportSignatureList")]
        [HttpGet]
        public IEnumerable<SignatureExcelExtraModel> ExtraExportSignatureList([FromUri] SignatureExportRequestModel model)
        {
            if (!ModelState.IsValid || model == null)
            {
                throw new Exception("导出Excel请求参数不正确.");
            }
            var mongoDb = MongoDbInstanceStore.DataStoreInstance;
            var builder = Builders<BsonDocument>.Filter;
            FilterDefinition<BsonDocument> filter = builder.Empty;
            FilterDefinition<BsonDocument> TimeFilter;
            FilterDefinition<BsonDocument> AreaFilter;
            if (model.Mode == ExportMode.range)
            {
                var rangeFilter1 = builder.Gte("FlightDetail.Fdt", model.Range[0]);
                var rangeFilter2 = builder.Lte("FlightDetail.Fdt", model.Range[1]);
                TimeFilter = builder.And(rangeFilter1, rangeFilter2);
            }
            else if (model.Mode == ExportMode.month)
            {
                var monthFilter1 = builder.Gte("FlightDetail.Fdt", model.Month);
                var monthFilter2 = builder.Lte("FlightDetail.Fdt", model.Month.AddMonths(1));
                TimeFilter = builder.And(monthFilter1, monthFilter2);
            }
            else
            {
                TimeFilter = builder.And(builder.Gte("Time", DateTime.Now), builder.Lte("Time", DateTime.Now));
            }
            var FltFilter = model.Flt.IsEmpty() ? builder.Empty : builder.Regex("Flt", new BsonRegularExpression(".*" + model.Flt + ".*", "i"));
            var StandFilter = model.Stand.IsEmpty() ? builder.Empty : builder.Eq("Stand", model.Stand);
            var AirlineFilter = model.Airline.IsEmpty() ? builder.Empty : builder.Eq("Airline", model.Airline);
            var Status = model.Status.HasValue ? builder.Eq("Stauts", (int)model.Status) : builder.Empty;
            var FTypeFilter = model.FType.HasValue ? builder.Eq("FType", (int)model.FType) : builder.Empty;
            var PlaneTypeFilter = model.PlaneType.IsEmpty() ? builder.Empty : builder.Eq("PlaneType", model.PlaneType);
            var PnumFilter = model.Pnum.IsEmpty() ? builder.Empty : builder.Eq("Pnum", model.Pnum);
            var UserNameFilter = model.UserName.IsEmpty() ? builder.Empty : builder.Eq("UserName", model.UserName);
            var STypeFilter = model.SType.HasValue ? builder.Eq("SType", (int)model.SType) : builder.Empty;
            var AbandonedFilter = builder.Or(builder.Eq("abandoned", false), builder.Not(builder.Exists("abandoned")));
            //筛选区域
            var standArea = new StandArea();
            var type = standArea.GetType().GetProperty(model.Area.ToString());
            if (type != null)
            {
                var values = type.GetValue(standArea) as IEnumerable<string>;
                AreaFilter = builder.In("Stand", values);
            }
            else
            {
                AreaFilter = builder.Empty;
            }
            filter = builder.And(TimeFilter, FltFilter, StandFilter, AirlineFilter, Status, FTypeFilter, PlaneTypeFilter,PnumFilter, UserNameFilter, STypeFilter, AreaFilter,AbandonedFilter);
            var softBuilder = Builders<BsonDocument>.Sort;
            var sort = softBuilder.Ascending("Time");
            PipelineDefinition<BsonDocument, BsonDocument> pipeline = new BsonDocument[]{};
            #region Project To Combine Auto Data And Manual Data

            ProjectionDefinition<BsonDocument, BsonDocument> project1 = new BsonDocument()
                        .Add("Fdt","$FlightDetail.Fdt")
                        .Add("No", 1.0)
                        .Add("Pnum", 1.0)
                        .Add("Flt", 1.0)
                        .Add("Airline", 1.0)
                        .Add("PlaneType", 1.0)
                        .Add("TLSign", new BsonDocument()
                            .Add("$cond", new BsonDocument()
                                .Add("if", new BsonDocument()
                                    .Add("$eq", new BsonArray()
                                        .Add("$FType")
                                        .Add(1.0)
                                    )
                                )
                                .Add("then", "\u51FA\u53D1")
                                .Add("else", "\u5230\u8FBE")
                            )
                        )
                        .Add("fltr", new BsonDocument()
                            .Add("$cond", new BsonDocument()
                                .Add("if", new BsonDocument()
                                    .Add("$eq", new BsonArray()
                                        .Add("$FType")
                                        .Add(1.0)
                                    )
                                )
                                .Add("then", "$FlightDetail.Ddetail.d_fltR")
                                .Add("else", "$FlightDetail.Adetail.a_fltR")
                            )
                        )
                        .Add("fltRType", new BsonDocument()
                            .Add("$cond", new BsonDocument()
                                .Add("if", new BsonDocument()
                                    .Add("$eq", new BsonArray()
                                        .Add("$FType")
                                        .Add(1.0)
                                    )
                                )
                                .Add("then", "$FlightDetail.Ddetail.d_fltRType")
                                .Add("else", "$FlightDetail.Adetail.a_fltRType")
                            )
                        )
                        .Add("fltk", new BsonDocument()
                            .Add("$cond", new BsonDocument()
                                .Add("if", new BsonDocument()
                                    .Add("$eq", new BsonArray()
                                        .Add("$FType")
                                        .Add(1.0)
                                    )
                                )
                                .Add("then", "$FlightDetail.Ddetail.d_fltk")
                                .Add("else", "$FlightDetail.Adetail.a_fltk")
                            )
                        )
                        .Add("Time", 1.0)
                        .Add("FType",1.0)
                        .Add("psData", 1.0)
                        .Add("pbData", 1.0)
                        .Add("cbData", 1.0)
                        .Add("gData", 1.0)
                        .Add("FinalBridgeData", new BsonDocument()
                                .Add("Bridge", new BsonDocument()
                                        .Add("$cond", new BsonDocument()
                                                .Add("if", new BsonDocument()
                                                        .Add("$anyElementTrue", new BsonArray()
                                                                .Add(new BsonArray()
                                                                        .Add("$bridgeData.Bridge")
                                                                        .Add("$AutobridgeData.Bridge")
                                                                )
                                                        )
                                                )
                                                .Add("then", new BsonDocument()
                                                        .Add("beginTime", new BsonDocument()
                                                                .Add("$ifNull", new BsonArray()
                                                                        .Add("$bridgeData.Bridge.beginTime")
                                                                        .Add("$AutobridgeData.Bridge.beginTime")
                                                                )
                                                        )
                                                        .Add("endTime", new BsonDocument()
                                                                .Add("$ifNull", new BsonArray()
                                                                        .Add("$bridgeData.Bridge.endTime")
                                                                        .Add("$AutobridgeData.Bridge.endTime")
                                                                )
                                                        )
                                                        .Add("UseType", new BsonDocument()
                                                                .Add("$ifNull", new BsonArray()
                                                                        .Add("$bridgeData.Bridge.UseType")
                                                                        .Add("$AutobridgeData.Bridge.UseType")
                                                                )
                                                        )
                                                )
                                                .Add("else", BsonNull.Value)
                                        )
                                )
                        )
                        .Add("FinalPcaData", new BsonDocument()
                                .Add("Pca", new BsonDocument()
                                        .Add("$cond", new BsonDocument()
                                                .Add("if", new BsonDocument()
                                                        .Add("$anyElementTrue", new BsonArray()
                                                                .Add(new BsonArray()
                                                                        .Add("$pcaData.Pca")
                                                                        .Add("$AutopcaData.Pca")
                                                                )
                                                        )
                                                )
                                                .Add("then", new BsonDocument()
                                                        .Add("beginTime", new BsonDocument()
                                                                .Add("$ifNull", new BsonArray()
                                                                        .Add("$pcaData.Pca.beginTime")
                                                                        .Add("$AutopcaData.Pca.beginTime")
                                                                )
                                                        )
                                                        .Add("endTime", new BsonDocument()
                                                                .Add("$ifNull", new BsonArray()
                                                                        .Add("$pcaData.Pca.endTime")
                                                                        .Add("$AutopcaData.Pca.endTime")
                                                                )
                                                        )
                                                        .Add("UseType", new BsonDocument()
                                                                .Add("$ifNull", new BsonArray()
                                                                        .Add("$pcaData.Pca.UseType")
                                                                        .Add("$AutopcaData.Pca.UseType")
                                                                )
                                                        )
                                                )
                                                .Add("else", BsonNull.Value)
                                        )
                                )
                        )
                        .Add("FinalAdapterData", new BsonDocument()
                                .Add("Adapter", new BsonDocument()
                                        .Add("$cond", new BsonDocument()
                                                .Add("if", new BsonDocument()
                                                        .Add("$anyElementTrue", new BsonArray()
                                                                .Add(new BsonArray()
                                                                        .Add("$adapterData.Adapter")
                                                                        .Add("$AutoadapterData.Adapter")
                                                                )
                                                        )
                                                )
                                                .Add("then", new BsonDocument()
                                                        .Add("beginTime", new BsonDocument()
                                                                .Add("$ifNull", new BsonArray()
                                                                        .Add("$adapterData.Adapter.beginTime")
                                                                        .Add("$AutoadapterData.Adapter.beginTime")
                                                                )
                                                        )
                                                        .Add("endTime", new BsonDocument()
                                                                .Add("$ifNull", new BsonArray()
                                                                        .Add("$adapterData.Adapter.endTime")
                                                                        .Add("$AutoadapterData.Adapter.endTime")
                                                                )
                                                        )
                                                        .Add("UseType", new BsonDocument()
                                                                .Add("$ifNull", new BsonArray()
                                                                        .Add("$adapterData.Adapter.UseType")
                                                                        .Add("$AutoadapterData.Adapter.UseType")
                                                                )
                                                        )
                                                )
                                                .Add("else", BsonNull.Value)
                                        )
                                )
                        );


            #endregion
            #region Project To Make Final Data

            ProjectionDefinition<BsonDocument, BsonDocument> project2 = new BsonDocument()
                        .Add("Fdt", 1.0)
                        .Add("No", 1.0)
                        .Add("Pnum", 1.0)
                        .Add("Flt", 1.0)
                        .Add("Airline", 1.0)
                        .Add("PlaneType", 1.0)
                        .Add("TLSign",1.0)
                        .Add("fltr", 1.0)
                        .Add("fltRType", 1.0)
                        .Add("fltk", 1.0)
                        .Add("Time", 1.0)
                        .Add("FType", 1.0)
                        .Add("psData", 1.0)
                        .Add("pbData", 1.0)
                        .Add("cbData", 1.0)
                        .Add("gData", 1.0)
                        .Add("bridgeData", new BsonDocument()
                                .Add("Bridge", new BsonDocument()
                                        .Add("$cond", new BsonDocument()
                                                .Add("if", new BsonDocument()
                                                        .Add("$allElementsTrue", new BsonArray()
                                                                .Add(new BsonArray()
                                                                        .Add("$FinalBridgeData.Bridge")
                                                                )
                                                        )
                                                )
                                                .Add("then", new BsonDocument()
                                                        .Add("beginTime", "$FinalBridgeData.Bridge.beginTime")
                                                        .Add("endTime", "$FinalBridgeData.Bridge.endTime")
                                                        .Add("UseType", "$FinalBridgeData.Bridge.UseType")
                                                        .Add("usingTime", new BsonDocument()
                                                                .Add("$cond", new BsonDocument()
                                                                        .Add("if", new BsonDocument()
                                                                                .Add("$allElementsTrue", new BsonArray()
                                                                                        .Add(new BsonArray()
                                                                                                .Add("$FinalBridgeData.Bridge.beginTime")
                                                                                                .Add("$FinalBridgeData.Bridge.endTime")
                                                                                                .Add(new BsonDocument()
                                                                                                        .Add("$gte", new BsonArray()
                                                                                                                .Add("$FinalBridgeData.Bridge.endTime")
                                                                                                                .Add("$FinalBridgeData.Bridge.beginTime")
                                                                                                        )
                                                                                                )
                                                                                        )
                                                                                )
                                                                        )
                                                                        .Add("then", new BsonDocument()
                                                                                .Add("$trunc", new BsonDocument()
                                                                                        .Add("$divide", new BsonArray()
                                                                                                .Add(new BsonDocument()
                                                                                                        .Add("$subtract", new BsonArray()
                                                                                                                .Add("$FinalBridgeData.Bridge.endTime")
                                                                                                                .Add("$FinalBridgeData.Bridge.beginTime")
                                                                                                        )
                                                                                                )
                                                                                                .Add(60000.0)
                                                                                        )
                                                                                )
                                                                        )
                                                                        .Add("else", 0)
                                                                )
                                                        )
                                                )
                                                .Add("else", BsonNull.Value)
                                        )
                                )
                        )
                        .Add("pcaData", new BsonDocument()
                                .Add("Pca", new BsonDocument()
                                        .Add("$cond", new BsonDocument()
                                                .Add("if", new BsonDocument()
                                                        .Add("$allElementsTrue", new BsonArray()
                                                                .Add(new BsonArray()
                                                                        .Add("$FinalPcaData.Pca")
                                                                )
                                                        )
                                                )
                                                .Add("then", new BsonDocument()
                                                        .Add("beginTime", "$FinalPcaData.Pca.beginTime")
                                                        .Add("endTime", "$FinalPcaData.Pca.endTime")
                                                        .Add("UseType", "$FinalPcaData.Pca.UseType")
                                                        .Add("usingTime", new BsonDocument()
                                                                .Add("$cond", new BsonDocument()
                                                                        .Add("if", new BsonDocument()
                                                                                .Add("$allElementsTrue", new BsonArray()
                                                                                        .Add(new BsonArray()
                                                                                                .Add("$FinalPcaData.Pca.beginTime")
                                                                                                .Add("$FinalPcaData.Pca.endTime")
                                                                                                .Add(new BsonDocument()
                                                                                                        .Add("$gte", new BsonArray()
                                                                                                                .Add("$FinalPcaData.Pca.endTime")
                                                                                                                .Add("$FinalPcaData.Pca.beginTime")
                                                                                                        )
                                                                                                )
                                                                                        )
                                                                                )
                                                                        )
                                                                        .Add("then", new BsonDocument()
                                                                                .Add("$trunc", new BsonDocument()
                                                                                        .Add("$divide", new BsonArray()
                                                                                                .Add(new BsonDocument()
                                                                                                        .Add("$subtract", new BsonArray()
                                                                                                                .Add("$FinalPcaData.Pca.endTime")
                                                                                                                .Add("$FinalPcaData.Pca.beginTime")
                                                                                                        )
                                                                                                )
                                                                                                .Add(60000.0)
                                                                                        )
                                                                                )
                                                                        )
                                                                        .Add("else", 0)
                                                                )
                                                        )
                                                )
                                                .Add("else", BsonNull.Value)
                                        )
                                )
                        )
                        .Add("adapterData", new BsonDocument()
                                .Add("Adapter", new BsonDocument()
                                        .Add("$cond", new BsonDocument()
                                                .Add("if", new BsonDocument()
                                                        .Add("$allElementsTrue", new BsonArray()
                                                                .Add(new BsonArray()
                                                                        .Add("$FinalAdapterData.Adapter")
                                                                )
                                                        )
                                                )
                                                .Add("then", new BsonDocument()
                                                        .Add("beginTime", "$FinalAdapterData.Adapter.beginTime")
                                                        .Add("endTime", "$FinalAdapterData.Adapter.endTime")
                                                        .Add("UseType", "$FinalAdapterData.Adapter.UseType")
                                                        .Add("usingTime", new BsonDocument()
                                                                .Add("$cond", new BsonDocument()
                                                                        .Add("if", new BsonDocument()
                                                                                .Add("$allElementsTrue", new BsonArray()
                                                                                        .Add(new BsonArray()
                                                                                                .Add("$FinalAdapterData.Adapter.beginTime")
                                                                                                .Add("$FinalAdapterData.Adapter.endTime")
                                                                                                .Add(new BsonDocument()
                                                                                                        .Add("$gte", new BsonArray()
                                                                                                                .Add("$FinalAdapterData.Adapter.endTime")
                                                                                                                .Add("$FinalAdapterData.Adapter.beginTime")
                                                                                                        )
                                                                                                )
                                                                                        )
                                                                                )
                                                                        )
                                                                        .Add("then", new BsonDocument()
                                                                                .Add("$trunc", new BsonDocument()
                                                                                        .Add("$divide", new BsonArray()
                                                                                                .Add(new BsonDocument()
                                                                                                        .Add("$subtract", new BsonArray()
                                                                                                                .Add("$FinalAdapterData.Adapter.endTime")
                                                                                                                .Add("$FinalAdapterData.Adapter.beginTime")
                                                                                                        )
                                                                                                )
                                                                                                .Add(60000.0)
                                                                                        )
                                                                                )
                                                                        )
                                                                        .Add("else", 0)
                                                                )
                                                        )
                                                )
                                                .Add("else", BsonNull.Value)
                                        )
                                )
                        );


            #endregion
            #region Project To Make Correct Format

            ProjectionDefinition<BsonDocument, SignatureExcelExtraModel> project3 = new BsonDocument()
                .Add("Fdt", 1.0)
                .Add("No", 1.0)
                .Add("Pnum", 1.0)
                .Add("Flt", 1.0)
                .Add("Airline", 1.0)
                .Add("PlaneType", 1.0)
                .Add("TLSign", 1.0)
                .Add("fltr", 1.0)
                .Add("fltRType", 1.0)
                .Add("fltk", 1.0)
                .Add("Time", 1.0)
                .Add("FType", 1.0)
                .Add("psData", 1.0)
                .Add("pbData", 1.0)
                .Add("cbData", 1.0)
                .Add("gData", 1.0)
                .Add("BridgeBeginTime", "$bridgeData.Bridge.beginTime")
                .Add("BridgeEndTime", "$bridgeData.Bridge.endTime")
                .Add("BridgeUseType", "$bridgeData.Bridge.UseType")
                .Add("BridgeUsingTime2", new BsonDocument()
                                .Add("$cond", new BsonDocument()
                                        .Add("if", new BsonDocument()
                                                .Add("$or", new BsonArray()
                                                        .Add(new BsonDocument()
                                                                .Add("$eq", new BsonArray()
                                                                        .Add("$bridgeData.Bridge.UseType")
                                                                        .Add(1.0)
                                                                )
                                                        )
                                                        .Add(new BsonDocument()
                                                                .Add("$eq", new BsonArray()
                                                                        .Add("$bridgeData.Bridge.UseType")
                                                                        .Add(2.0)
                                                                )
                                                        )
                                                )
                                        )
                                        .Add("then", "$bridgeData.Bridge.usingTime")
                                        .Add("else", 0)
                                )
                        )
                        .Add("BridgeUsingTime1", new BsonDocument()
                                .Add("$cond", new BsonDocument()
                                        .Add("if", new BsonDocument()
                                                .Add("$eq", new BsonArray()
                                                        .Add("$bridgeData.Bridge.UseType")
                                                        .Add(0.0)
                                                )
                                        )
                                        .Add("then", "$bridgeData.Bridge.usingTime")
                                        .Add("else", 0)
                                )
                        )
                .Add("PcaBeginTime", "$pcaData.Pca.beginTime")
                .Add("PcaEndTime", "$pcaData.Pca.endTime")
                //.Add("PcaUseType", "$pcaData.Pca.UseType")
                .Add("PcaUsingTime", "$pcaData.Pca.usingTime")
                .Add("AdapterBeginTime", "$adapterData.Adapter.beginTime")
                .Add("AdapterEndTime", "$adapterData.Adapter.endTime")
                //.Add("AdapterUseType", "$adapterData.Adapter.UseType")
                .Add("AdapterUsingTime", "$adapterData.Adapter.usingTime");

            #endregion
            var pipelineNew = pipeline.Match(filter).Sort(sort).Project(project1).Project(project2).Project(project3);
            IEnumerable<SignatureExcelExtraModel> dBdata;
            dBdata = mongoDb.GetDataAggregate("DataStore", "SignatureStore", pipelineNew) as IEnumerable<SignatureExcelExtraModel>;
            // var dBdata = mongoDb.GetDataAggregate("DataStore", "SignatureStore", pipeline) as IEnumerable<SignatureExcelModel>; 
            //var dBdata = mongoDb.GetDataMany<BsonDocument, SignatureExcelModel>("DataStore", "SignatureStore", filter,sort, 0, 0, projection);
            return dBdata;
        }
        [Route("SpecialExportSignatureList")]
        [HttpGet]
        public IEnumerable<SignatureSpecialExcelFinalModel> SpecialExportSignatureList([FromUri] SignatureExportSpecialRequestModel model)
        {
            try
            {
                if (!ModelState.IsValid || model == null)
                {
                    throw new Exception("导出Excel请求参数不正确.");
                }
                var mongoDb = MongoDbInstanceStore.DataStoreInstance;
                var builder = Builders<BsonDocument>.Filter;
                FilterDefinition<BsonDocument> filter = builder.Empty;
                FilterDefinition<BsonDocument> TimeFilter;
                FilterDefinition<BsonDocument> AbandonedFilter;
                if (model.Mode == ExportMode.range)
                {
                    var rangeFilter1 = builder.Gte("FlightDetail.Fdt", model.Range[0]);
                    var rangeFilter2 = builder.Lte("FlightDetail.Fdt", model.Range[1]);
                    TimeFilter = builder.And(rangeFilter1, rangeFilter2);
                }
                else if (model.Mode == ExportMode.month)
                {
                    var monthFilter1 = builder.Gte("FlightDetail.Fdt", model.Month);
                    var monthFilter2 = builder.Lte("FlightDetail.Fdt", model.Month.AddMonths(1));
                    TimeFilter = builder.And(monthFilter1, monthFilter2);
                }
                else
                {
                    TimeFilter = builder.And(builder.Gte("Time", DateTime.Now), builder.Lte("Time", DateTime.Now));
                }

                AbandonedFilter = builder.Or(builder.Eq("abandoned", false), builder.Not(builder.Exists("abandoned")));
                filter = builder.And(TimeFilter, AbandonedFilter);
                var softBuilder = Builders<BsonDocument>.Sort;
                var sort = softBuilder.Ascending("u_t");
                PipelineDefinition<BsonDocument, BsonDocument> pipeline = new BsonDocument[] { };
                #region projection
                ProjectionDefinition<BsonDocument, SignatureSpecialExcelModel> project1 = new BsonDocument()
                    .Add("ExcuteTime", "$FlightDetail.Fdt")
                    .Add("PlanNo", "")
                    .Add("Flt", new BsonDocument()
                        .Add("$ifNull", new BsonArray()
                            .Add("$a_flt")
                            .Add(new BsonDocument()
                                .Add("$ifNull", new BsonArray()
                                    .Add("$d_flt")
                                    .Add("")
                                )
                            )
                        )
                    )
                    .Add("Airline", "$airline")
                    .Add("Pnum", "$pnum")
                    .Add("Pmodel", "$pmodel")
                    .Add("BridgeDetail", "$BridgeDetailData");

                #endregion
                var pipelineNew = pipeline.Match(filter).Sort(sort).Project(project1);
                IEnumerable<SignatureSpecialExcelModel> dBdata;
                dBdata = mongoDb.GetDataAggregate("DataStore", "FlightMissionList", pipelineNew) as IEnumerable<SignatureSpecialExcelModel>;
                var finalData = new List<SignatureSpecialExcelFinalModel>();
                foreach (var item in dBdata)
                {
                    var tempBridgeDetail = item.BridgeDetail;
                    if (tempBridgeDetail == null)
                    {
                        var tempObj = new SignatureSpecialExcelFinalModel()
                        {
                            ExcuteTime = item.ExcuteTime,
                            PlanNo = item.PlanNo,
                            Flt = item.Flt,
                            Airline = item.Airline,
                            Pnum = item.Pnum,
                            Pmodel = item.Pmodel
                        };
                        finalData.Add(tempObj);
                    }
                    else
                    {
                        var detailItemTemp = new List<DetailDataModel>();
                        var detailItemCount = new List<int>();
                        int maxCount = 0;
                        foreach (var detailItem in tempBridgeDetail)
                        {
                            detailItemTemp.Add(detailItem);
                            detailItemCount.Add(detailItem.DetailDatas.Count);
                        }
                        maxCount = detailItemCount.Max();
                        for (int i = 0; i < maxCount; i++)
                        {
                            var count = 0;
                            DateTime? bTime = null;
                            DateTime? eTime = null;
                            decimal? uTime = null;
                            foreach (var itemTemp in detailItemTemp)
                            {
                                if (i - 1 > itemTemp.DetailDatas.Count)
                                {
                                    continue;
                                }
                                try
                                {
                                    var test = itemTemp.DetailDatas[i];
                                    if (test != null)
                                    {
                                        bTime = itemTemp.DetailDatas[i].beginTime;
                                        eTime = itemTemp.DetailDatas[i].endTime;
                                        uTime = itemTemp.DetailDatas[i].usingTime;
                                        count++;
                                    }
                                }
                                catch (Exception e)
                                {
                                    // ignored
                                }
                            }
                            var tempObj = new SignatureSpecialExcelFinalModel()
                            {
                                ExcuteTime = item.ExcuteTime,
                                PlanNo = item.PlanNo,
                                Flt = item.Flt,
                                Airline = item.Airline,
                                Pnum = item.Pnum,
                                Pmodel = item.Pmodel,
                                BridgeBeginTime = bTime != null ? bTime.Value.ToLocalTime().ToString("yyyyMMddHHmm") : "",
                                BridgeEndTime = eTime != null ? eTime.Value.ToLocalTime().ToString("yyyyMMddHHmm") : "",
                                BridgeUsingTime1 = count < 2 ? uTime : 0,
                                BridgeUsingTime2 = count >= 2 ? uTime : 0

                            };
                            finalData.Add(tempObj);
                        }
                    }


                }
                return finalData;
            }
            catch (Exception e)
            {
                var logger = NLog.LogManager.GetLogger("AppRunLog");
                logger.Error(e);
                Console.WriteLine(e);
                throw;
            }
            
        }
        /// <summary>
        /// 申请获得连接WebSocket的权限
        /// </summary>
        /// <returns>返回WebSocketToken<see cref="WebSocketTokenModel"/></returns>
        [Route("GetWebSocketToken")]
        public HttpResponseMessage GetWebSocketToken([FromUri]WebSocketRequsetTokenModel model)
        {
            if (!ModelState.IsValid)
            {
                return Request.CreateResponse(HttpStatusCode.BadRequest, ModelState);
            }
            var user = RequestContext.Principal.Identity.Name;
            var mongoDb = MongoDbInstanceStore.DataStoreInstance;
            var TempEnum = new WebSocketAction();
            // var hash = BCrypt.Net.BCrypt.HashString(user + DateTime.Now.Ticks);
            var hash = Guid.NewGuid().ToString();
            var addDocument=new BsonDocument()
            {
                new BsonElement("user",user),
                new BsonElement("WsToken",hash),
                new BsonElement("WsAct",model.WsAct),
                new BsonElement("expire",DateTime.Now.AddMinutes(5))
            };
            var count = mongoDb.InsertSingleDocument("DataStore", "WebSocketPool", addDocument);
            if (count>0)
            {
                var result = new WebSocketTokenModel()
                {
                    User = user,
                    Token = hash
                };
                return Request.CreateResponse(HttpStatusCode.OK, result);
            }
            ModelState.AddModelError("error","获取Token失败");
            return Request.CreateResponse(HttpStatusCode.BadRequest, ModelState);
        }
        /// <summary>
        /// 请求连接WebSocket
        /// </summary>
        /// /// <returns>返回HTTP返回码,如出错,将同时返回出错信息。<see cref="HttpStatusCode"/></returns>
        [Route("ConnectWebSocket")]
        [HttpGet]
        [AllowAnonymous]
        public HttpResponseMessage ConnectWebSocket([FromUri]WebSocketRequestModel model)
        {
            if (!ModelState.IsValid)
            {
                return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
            }
            var mongoDb = MongoDbInstanceStore.DataStoreInstance;
            var filterBuilder = Builders<BsonDocument>.Filter;
            var userFilter = filterBuilder.Eq("user", model.User);
            var tokenFilter = filterBuilder.Eq("WsToken", model.Token);
            var actFilter = filterBuilder.Eq("WsAct", model.WsAct);
            var expireFilter = filterBuilder.Gte("expire", DateTime.Now);
            var filter = filterBuilder.And(userFilter, tokenFilter, actFilter, expireFilter);
            var result = mongoDb.CountData("DataStore", "WebSocketPool", filter);
            if (result<1)
            {
                ModelState.AddModelError("error","没有检测到连接WebSocket的授权!");
                return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
            }
            try
            {
                //HttpContext.Current.GetOwinContext().Request.
                HttpContext.Current.AcceptWebSocketRequest(new WebSocketHelper().ProcessHandler); //在服务器端接受Web Socket请求，传入的函数作为Web Socket的处理函数，待Web Socket建立后该函数会被调用，在该函数中可以对Web Socket进行消息收发

            }
            catch (Exception e)
            {
                return Request.CreateErrorResponse(HttpStatusCode.BadRequest, e); //构造同意切换至Web Socket的Response.
                // throw;
            }
            //HttpContext.Current.AcceptWebSocketRequest(WebSocketHelper.ProcessHandler); //在服务器端接受Web Socket请求，传入的函数作为Web Socket的处理函数，待Web Socket建立后该函数会被调用，在该函数中可以对Web Socket进行消息收发

            return Request.CreateResponse(HttpStatusCode.SwitchingProtocols); //构造同意切换至Web Socket的Response.
        }
        /// <summary>
        /// 获取表头
        /// </summary>
        /// <param name="tableName">输入表格名称</param>
        /// <returns>返回HTTP返回码,如出错,将同时返回出错信息。<see cref="TableHeadModel"/></returns>
        [Route("GetTitleHead")]
        public HttpResponseMessage GetTitleHead([FromUri] string tableName)
        {
           //  var qqq=UserManager
            var mongoDb = MongoDbInstanceStore.DataStoreInstance;
            var builder = Builders<BsonDocument>.Filter;
            var filter=builder.Eq("Table", tableName);
            var projection = Builders<BsonDocument>.Projection.Exclude("_id");
            var dBdata = mongoDb.GetDataSingel<BsonDocument, BsonDocument>("DataStore", "TitleStore", filter, projection);
            if (dBdata==null)
            {
                return Request.CreateResponse(HttpStatusCode.OK, new string[1]);
            }

            var resultArray = dBdata.ToJson();
            return Request.CreateResponse(HttpStatusCode.OK, (JArray)JsonConvert.DeserializeObject(resultArray));


        }
        /// <summary>
        /// 获取区域列表
        /// </summary>
        /// <returns>返回区域对象key为字符串,val为值<see cref="StandAreaEnum"/></returns>
        [Route("GetArea")]
        public HttpResponseMessage GetArea()
        {

            var row = new Dictionary<string, int>();
            foreach (StandAreaEnum area in Enum.GetValues(typeof(StandAreaEnum)))
            {
                row.Add(area.ToString(), (int)area);
            }
            return Request.CreateResponse(HttpStatusCode.Accepted, row);
        }
        /// <summary>
        /// 获取签单状态列表
        /// </summary>
        /// <returns>返回状态对象key为字符串,val为值<see cref="SignatureStatus"/></returns>
        [Route("GetStatusList")]
        public HttpResponseMessage GetStatusList()
        {
            var row = new Dictionary<string, int>();
            foreach (SignatureStatus status in Enum.GetValues(typeof(SignatureStatus)))
            {
                row.Add(status.ToString(), (int)status);
            }
            return Request.CreateResponse(HttpStatusCode.Accepted, row);
        }
        /// <summary>
        /// 获取航班类型
        /// </summary>
        /// <returns>返回状态对象key为字符串,val为值<see cref="FlightType"/></returns>
        [Route("GetFtype")]
        public HttpResponseMessage GetFtype()
        {
            var row = new Dictionary<string, int>();
            foreach (FlightType ftype in Enum.GetValues(typeof(FlightType)))
            {
                row.Add(ftype.ToString(), (int)ftype);
            }
            return Request.CreateResponse(HttpStatusCode.Accepted, row);
        }
        [Route("GetSType")]
        public HttpResponseMessage GetSType()
        {
            var row = new Dictionary<string, int>();
            foreach (SignatureType ftype in Enum.GetValues(typeof(SignatureType)))
            {
                row.Add(ftype.ToString(), (int)ftype);
            }
            return Request.CreateResponse(HttpStatusCode.Accepted, row);
        }
        /// <summary>
        /// 获取登机桥和梯车使用模式
        /// </summary>
        /// <returns>返回状态对象key为字符串,val为值<see cref="BridgeUseType"/></returns>
        [Route("GetBridgeUseType")]
        public HttpResponseMessage GetBridgeUseType()
        {
            var row = new Dictionary<string, int>();
            foreach (BridgeUseType ftype in Enum.GetValues(typeof(BridgeUseType)))
            {
                row.Add(ftype.ToString(), (int)ftype);
            }
            return Request.CreateResponse(HttpStatusCode.Accepted, row);
        }
        /// <summary>
        /// 获取桥载使用模式
        /// </summary>
        /// <returns>返回状态对象key为字符串,val为值<see cref="BridgeLoadUseType"/></returns>
        [Route("GetBridgeLoadUseType")]
        public HttpResponseMessage GetBridgeLoadUseType()
        {
            var row = new Dictionary<string, int>();
            foreach (BridgeLoadUseType ftype in Enum.GetValues(typeof(BridgeLoadUseType)))
            {
                row.Add(ftype.ToString(), (int)ftype);
            }
            return Request.CreateResponse(HttpStatusCode.Accepted, row);
        }
        /// <summary>
        /// 获取航空公司列表
        /// </summary>
        /// <returns>返回航空公司列表,如出错,将同时返回出错信息。<see cref="TableHeadModel"/></returns>
        [Route("GetAirline")]
        public HttpResponseMessage GetAirline()
        {
            var flightMergeInstance = MongoDbInstanceStore.DataStoreInstance;
            var builder = Builders<Airline>.Filter;
            // var projection = Builders<BsonDocument>.Projection.Include("_id").Include("CNNM");
            var filter = builder.Empty;
            var userManager = Request.GetOwinContext().GetUserManager<ApplicationUserManager>();
            var userClaims = userManager.GetClaims(User.Identity.GetUserId());
            string userAirLine = null;
            foreach (var item in userClaims)
            {
                if (item.Type == "UserAirline")
                {
                    userAirLine = item.Value;
                }

            }
            if (userAirLine != null)
            {
                filter &= builder.Eq("Airline", userAirLine);
            }
            var dBdata = flightMergeInstance.GetDataMany<Airline, Airline>("DataStore", "coll_airline", filter);
            //if (dBdata == null)
            //{
            //    return Request.CreateResponse(HttpStatusCode.OK, new string[1]);
            //}

            //var resultArray = dBdata.ToJson();
            return Request.CreateResponse(HttpStatusCode.OK, dBdata);
        }
        /// <summary>
        /// 获取APP更新版本
        /// </summary>
        /// <param name="model">App新版本请求模型</param>
        /// <returns>更新数据<see cref="AppUpdateModel"/></returns>
        [Route("GetAppUpdate")]
        [AllowAnonymous]
        [ApiExplorerSettings(IgnoreApi = true)]
        public HttpResponseMessage GetAppUpdate([FromUri]AppUpdateRequestModel model)
        {
            var mongoDb = MongoDbInstanceStore.DataStoreInstance;
            var builder = Builders<AppUpdateModel>.Filter;
            var filter = builder.Empty;
            if (model?.versionCode != null)
            {
                filter &= builder.Eq("versionCode", model.versionCode);
            }
            var sortBuilder = Builders<AppUpdateModel>.Sort;
            var sort = sortBuilder.Descending("updateTime");
            var dBdata = mongoDb.GetDataSingel<AppUpdateModel, AppUpdateModel>("DataStore", "AppUpdate", filter, null, sort) as IEnumerable<AppUpdateModel>;
            var temp = dBdata.ToList()[0];
            return Request.CreateResponse(HttpStatusCode.OK, temp);
        }
        ///// <summary>
        ///// 测试用
        ///// </summary>
        ///// <returns></returns>
        //[Route("TestUpdate")]
        //public HttpResponseMessage UpdateDataTime()
        //{
        //    var mongoDb = MongoDbInstanceStore.DataStoreInstance;
        //    var builder = Builders<SignatureReturnModel>.Filter;
        //    var filter = builder.Empty;
        //    var update = Builders<SignatureReturnModel>.Update;
        //    var updateContent= update.Set(x => x.Time, DateTime.Now);
        //    var count = mongoDb.UpdateDocument("DataStore", "SignatureStore", filter, updateContent);
        //    Random random = new Random((int)(DateTime.Now.Ticks));
        //    return Request.CreateResponse(HttpStatusCode.OK, count);
        //}
    }
}
